Consider this example:
def A():
b = 1
def B():
# I can access 'b' from here.
print(b)
# But can i modify 'b' here?
B()
A()
For the code in the B function, the variable b is in a non-global, enclosing (outer) scope. How can I modify b from within B? I get an UnboundLocalError if I try it directly, and using global does not fix the problem since b is not global.
Python implements lexical, not dynamic scope - like almost all modern languages. The techniques here will not allow access to the caller's variables - unless the caller also happens to be an enclosing function - because the caller is not in scope. For more on this problem, see How can I access variables from the caller, even if it isn't an enclosing scope (i.e., implement dynamic scoping)?.
bis mutable. An assignment tobwill mask the outer scope.nonlocalhasn't been backported to 2.x. It's an intrinsic part of closure support.nonlocalkeyword is explained here: stackoverflow.com/questions/1261875/python-nonlocal-statement. The current question is a better canonical most of the time, since most askers will have a problem that is solved by thenonlocalkeyword, and not already be aware of it. However, that question is a useful reference, e.g. for people who have encounterednonlocalin someone else's code.nonlocalstatement. Python 2: use a hack (e.g. dummy class/dict/list) to contain nonlocals.