A closure is an inner function returned by an outer function that retains access to variables in the enclosing scope after the outer call ends. Each invocation of the outer function creates a new inner function and its captured values. section 7.11 section 7.5
A multiplier closure
def foo(x): def bar(y): return x * y return bar f = foo(10) print(f(20)) # 200 The returned function keeps access to x, even though foo has returned. Calling foo again creates another closure with its own enclosing value. section 7.5
Use closures when a returned function needs private configuration or persistent state:
- Capture configuration, such as allowed password characters, while exposing only the returned generator function. section 7.11
- Maintain state with nonlocal: assign to the enclosing variable instead of creating a new local variable. section 7.5
- Apply LEGB when diagnosing name resolution: Python checks the local, enclosing, global, and built-in namespaces in order. section 7.5
Figure 7.2 Python Tutor’s depiction of two password-generating functions
Visualize two password-generating closures and compare the separate functions created by separate outer invocations. section 7.11



















