In Python, functions are first-class — you can define one inside another and return it. A closure is such an inner function thatremembers the variables from the scope where it was created, even after that outer scope has finished running.
A function factory
The outer function's parameter is "baked into" each returned inner function:
def multiplier(factor):def multiply(n):return n * factor # 'factor' is captured from the outer scopereturn multiplydouble = multiplier(2)triple = multiplier(3)double(10) # 20 — remembers factor=2triple(10) # 30 — remembers factor=3
Remembering state
Closures can hold private, per-instance state without a class. Use nonlocal to modify a captured variable:
def make_counter():count = 0def increment():nonlocal count # modify the enclosing variablecount += 1return countreturn incrementc = make_counter()c() # 1c() # 2 — state persists between calls
Key takeaways
- 01A closure is an inner function that captures variables from its enclosing scope.
- 02It remembers those variables even after the outer function has returned.
- 03Use nonlocal to modify (not just read) a captured variable.
- 04Closures enable function factories and private per-instance state.
- 05They are the mechanism behind decorators.
