PYTHON ADVANCEDChapter 9 · Python Advanced
Closures
A function defined inside another function can use the outer function's variables, even after the outer function has finished. The inner function plus the variables it remembers is called a closure. Closures let you build customized functions on the fly. Use nonlocal when the inner function needs to change a remembered variable.
Worked example
How it reads
multiplyremembersfactorfrom the call that created it- Each call to
make_multipliermakes a separate closure with its own factor nonlocal countlets the inner function update the outer variable
Common mistakes
- Assigning to an outer variable without
nonlocalmakes a new local variable, which raises UnboundLocalError when you read it first.

Cloud tip: Decorators are built from closures: the wrapper function remembers the function it wraps.


