# scope.py x = 1 def f(): print "x inside f():", x f() def f(): x = 'foo' print "x inside f():", x f() print "global x:", x def f(): global x x = 'foo' f() print "global x:", x # Note how y doesn't exist in m until now import m m.y = 'xyz' m.g() # clean up for later section del x print # Shadowing def f(): print "Builtin str():", str(123) f() str = "abc" def f(): print "Global str:", str f() def f(): str = 456 print "Local str:", str f() print "Global str:", str del str print "Builtin str():", str(123) print # This nested scope works def f(): x = 1 def g(): print "x inside g():", x g() f() # This "nested scope" doesn't work def f(): x = 1 g() def g(): try: # Notice half this print executes before exception print "x inside g():", x except NameError: print "Sorry, can't access f()'s x" f() # Nested funcs can be closures def f(x): def g(y): print "x,y inside g():", x, y return g func = f(3) func('abc') # Cross-module scopes # Although h is local scope, it picks up m.y (not y) because # h's code object is still m.g h = m.g m.y = 4 y = 'foo' h() print # Now for some classes x = 'abc' class Foo: pass class Bar(Foo): pass class Baz(Bar): def f(self): self.x = 'xyz' def g(self): return x a = Baz() Foo.x = 5 print "a.x gets Foo.x:", a.x Bar.x = 'pdq' print "a.x gets Bar.x:", a.x a.f() print "a.x gets a.x:", a.x print "Foo().x gets Foo.x:", Foo().x print "global x is", a.g()