Python nonlocal statement
Compare this, without using nonlocal
:
x = 0
def outer():
x = 1
def inner():
x = 2
print("inner:", x)
inner()
print("outer:", x)
outer()
print("global:", x)
# inner: 2
# outer: 1
# global: 0
To this, using nonlocal
, where inner()
's x
is now also outer()
's x
:
x = 0
def outer():
x = 1
def inner():
nonlocal x
x = 2
print("inner:", x)
inner()
print("outer:", x)
outer()
print("global:", x)
# inner: 2
# outer: 2
# global: 0
If we were to use
global
, it would bindx
to the properly "global" value:x = 0 def outer(): x = 1 def inner(): global x x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x) # inner: 2 # outer: 1 # global: 2
In short, it lets you assign values to a variable in an outer (but non-global) scope. See PEP 3104 for all the gory details.
A google search for "python nonlocal" turned up the Proposal, PEP 3104, which fully describes the syntax and reasoning behind the statement. in short, it works in exactly the same way as the global
statement, except that it is used to refer to variables that are neither global nor local to the function.
Here's a brief example of what you can do with this. The counter generator can be rewritten to use this so that it looks more like the idioms of languages with closures.
def make_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
Obviously, you could write this as a generator, like:
def counter_generator():
count = 0
while True:
count += 1
yield count
But while this is perfectly idiomatic python, it seems that the first version would be a bit more obvious for beginners. Properly using generators, by calling the returned function, is a common point of confusion. The first version explicitly returns a function.