def Test(value):
def innerFunc():
print value
innerFunc()
def TestWithAssignment(value):
def innerFunc():
print value
value = "Changed value"
innerFunc()
Test("Hello 1")
# Prints "Hello 1"
TestWithAssignment("Hello 2")
# Throws UnboundLocalError: local variable 'value' referenced before assignment
# on the "print value" line
Why does the second one fail, given that the only difference is an assignment which comes after the print statement? I am pretty confused about this.
The issue is that Python wants you to be explicit and you want to be implicit. The execution model that Python uses binds names to the nearest available enclosing scope.
There is not (as far as I know) a way to walk up the scope in Python 2.x – you have
globals()andlocals()– but any scopes between the global and the local scope cannot be accessed (if this is not true, I’d love to be corrected).However, you can pass the local variable
valueinto your inner local scope:In Python 3 you have the new
nonlocalstatement that can be used to refer to the containing scope (Thanks @Thomas K).