4 ms·
Python supports closures even when the variable isn't a container. For instance: def add_double(n): x = n * 2 def add(y): retur
by voyou 11y ago
Python supports closures even when the variable isn't a container. For instance:
def add_double(n):
x = n * 2
def add(y):
return x + y
return add
f = add_double(1)
f(2) # -> 4
What python versions prior to 3 didn't support is rebinding a variable from an enclosing scope; not because of any fundamental feature of the implementation, but because there was no syntactic way to differentiate between a assigning to a variable in an enclosing scope, and creating a variable in the current scope. So x += 2 is short for x = x + 2, which python interprets as creating a new variable x in the current scope and then trying to access that variable before it's been assigned.
Python 3 introduced a syntax to specify that you wanted to assign to a variable from an enclosing scope, the 'nonlocal' keyword. So your example would be:
def even():
x = 0
def add():
nonlocal x
x += 2
return x
return add
count = even()
count() # → 2
count() # → 4