What is a closure in Python?
A closure is an inner function that remembers variables from the enclosing function even after that outer function has finished. It is how Python implements function factories and decorators with private state.
Explain it simply
A tiffin box keeps food warm after the person who packed it has left home. In the same way, an inner function carries along the variables it used from the place where it was created. Those variables stay alive for as long as the function does.
Example
def multiplier(n):
def times(x):
return x * n
return times
double = multiplier(2)
triple = multiplier(3)
print(double(10)) # Output: 20
print(triple(10)) # Output: 30
print(double.__closure__[0].cell_contents) # Output: 2multiplier has already returned, yet double still knows n = 2. Each call to multiplier creates its own separate n, so double and triple do not interfere.
Three things make a closure: a nested function, a reference to a variable from the outer function, and the outer function returning (or passing out) the inner one.
What to say in the interview
"A closure is an inner function bundled with the variables it captured from its enclosing scope. Python stores them in cells, visible through __closure__. I use them for function factories, simple stateful callbacks and decorators. To rebind a captured variable I need nonlocal."
Common mistakes
- Assuming the captured value is copied. It is the variable itself that is captured, which causes the late-binding surprise in loops.