A closure is an inner function returned by an outer function that keeps access to variables from the outer invocation. Each call to the outer function creates a separate returned function, allowing configuration to remain attached to later calls. section 6.12 section 6.5
A closure works through three connected ideas:
- The outer function accepts configuration, such as the characters allowed in a password. section 6.12
- The inner function uses that configuration through Python's LEGB lookup, finding variables in the enclosing function when they are not local. section 6.12 section 6.5
- The nonlocal keyword lets the inner function update a variable stored in the enclosing function rather than create a new local variable. section 6.5
A stateful closure
def foo(): call_counter = 0 def bar(y): nonlocal call_counter call_counter += 1 return f'y = {y}, call_counter = {call_counter}' return bar b = foo() for i in range(10, 100, 10): print(b(i)) The returned function remembers call_counter between calls, producing counts from 1 through 9. section 6.5
Visualizes two separately created password-generating closures and their retained enclosing values. section 6.12



















