Python scope
A reference to a variable, such as
foo(that is not explicitly qualified, such asflimflam.foo), is usually found in the innermost scope, i.e. the innermost textual block of code, where Python blocks are determined by indentation.foo = 3 def bar(): foo = 4 print(foo) bar()
If no reference is found in the innermost scope then search continues outwards from that scope to the module scope.
foo = 3 def bar(): foo = 4 def qux(): print(foo) qux() bar()
An exception is if a variable has been declared
globalin which case the reference is directly to the module scope.foo = 3 def bar(): foo = 4 def qux(): global foo print(foo) qux() bar()
What happens in each of the following cases?
foo = 32 def bar(): global foo foo = 88 return foo print(bar(), foo)
foo = 32 def bar(): foo = 88 return foo print(bar(), foo)
foo = 32 def bar(): return foo print(bar(), foo)
There's even an in-between case for a variable that's neither local nor global.
def outer(): x = "local" def inner(): nonlocal x x = "nonlocal" print("inner:", x) inner() print("outer:", x) outer()