# Scoping example for Python # g is in the middle symbol table g = 10 # f2 is in the middle symbol table f2 = 15 # f1 is in the middle symbol table f1 = 12 print 'initial:', g, f2, f1 # a new symbol table gets made when f1 is executed def f1(): # creates a new symbol g in the f1 symbol table # does not modify the middle symbol table entry g = 5 # used to see if we can access this h from elsewhere h = 20 global f2 print 'g, f2 in f1():', g, f2 # specifies that f2 should reference the middle symbol table # modifies f2 in the middle symbol table f2 = 25 print 'f2 in f1():',f2 # a new definition of f2, which actually modifies the middle symbol table def f2(): global g g = 6 print 'g,h in f2 post-assign:', g, h # a new definition of f3, which goes in the f1 symbol table def f3(): # a new definition of f2 in the f3 symbol table f2 = 6 print 'f2 in f3:', f2 # still refers to the function print 'f2 in f1 post f2 def:', f2 f2() # calls the function f2 # refers to the g in f1 print 'g in f1 post f2 call:', g f3() # calls the function f3 # still refers to the function print 'f2 in f1 post f3 call:', f2 # prints the global g print 'g, f2, f1 post f1 definition', g, f2, f1 # calls f1 f1() # prints the global versions print 'g, f2, f1 post f1 call', g, f2, f1 # f3 is not defined at the middle symbol table level try: f3() except: print 'unable to call f3()' # see if f2 is defined as the function f2()