Nonlocal Variables
suggest changePython 3 added a new keyword called nonlocal. The nonlocal keyword adds a scope override to the inner scope. You can read all about it in PEP 3104. This is best illustrated with a couple of code examples. One of the most common examples is to create a function that can increment:
def counter():
num = 0
def incrementer():
num += 1
return num
return incrementer
If you try running this code, you will receive an UnboundLocalError because the num variable is referenced before it is assigned in the innermost function. Let’s add nonlocal to the mix:
def counter():
num = 0
def incrementer():
nonlocal num
num += 1
return num
return incrementer
c = counter()
c() # = 1
c() # = 2
c() # = 3
nonlocal lets you assign to a variable in an enclosing function, not to a global variable. You can’t use nonlocal in counter itself: there is no enclosing function, so Python raises SyntaxError. Use nonlocal in a nested function.
(Note that the functionality presented here is better implemented using generators.)