What does it do, in Python 3.0? There's no documentation on the official Python website and help("nonlocal") does not work, either.
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.
Compare this, without using nonlocal:
>>> def outer():
x = 1
def inner():
x = 2
print("inner:", x)
inner()
print("outer:", x)
>>> outer()
inner: 2
outer: 1
To this, using nonlocal:
>>> def outer():
x = 1
def inner():
nonlocal x
x = 2
print("inner:", x)
inner()
print("outer:", x)
>>> outer()
inner: 2
outer: 2