An enclosing function is an outer function whose scope contains a nested function. The nested function can retain and use variables from the enclosing invocation after being returned. section 7.11
Use the enclosing scope to:
- Define a new inner function each time the outer function runs. section 7.11
- Configure returned functions with invocation-specific values, such as permitted password characters. section 7.11
- Understand name lookup through Python’s LEGB order: local, enclosing function, global, then built-ins. section 7.5
- Modify an enclosing variable from the nested function with the nonlocal declaration. section 7.5
A returned function retaining state
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() print(b(10)) # y = 10, call_counter = 1 print(b(20)) # y = 20, call_counter = 2 section 7.5
Figure 7.2 Python Tutor’s depiction of two password-generating functions
Visualize how separate invocations produce distinct password-generating functions with their own enclosing values. section 7.11

