4 ms·
I believe you are confusing closures with scope. Closures define the set of variables whose lifetime extends the function they are in because of their use in a
by espadrine 11y ago
I believe you are confusing closures with scope.
Closures define the set of variables whose lifetime extends the function they are in because of their use in another function.
For instance:
;; Function that returns a function that counts even numbers
(define (even)
(let ((x 0))
(lambda () (set! x (+ x 2)) x)))
(define count (even))
(count) ; → 2
(count) ; → 4
In Python:
def even():
x = 0
def add():
x += 2
return x
return add
count = even()
count() # → UnboundLocalError: local variable 'x' referenced before assignment
That said, Python does support a less convenient style of closures — it works if the variable is a container (such as a list, a dictionary or an object).
- voyou 11y agoPython 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