Advanced·6 min·advanced · functions
Closures & nonlocal
Closures & nonlocal
A closure is a function that captures variables from its enclosing scope.
Why nonlocal?
By default, assigning to a name inside a function creates a new local. nonlocal says "no, write to the outer variable."
When closures are useful
- Function factories (
make_counter,make_adder) - Lightweight state without a class
- Decorators (every decorator is a closure)
Gotcha
Classic loop pitfall: [lambda: i for i in range(3)] — all three lambdas see i == 2. Capture explicitly with a default argument: lambda i=i: i.
Try it
- Write
make_adder(n)that returns a function addingnto its argument. - What does
[f() for f in [lambda: i for i in range(3)]]produce?