What is a closure in Python, and how does a nested function keep state between calls?
A closure is a function that keeps access to the variables of the scope where it was defined, even after that scope has finished running.
Here is how that works in practice. A factory function creates a counter variable. It then defines a smaller function inside itself, and that smaller function reads the counter and updates it. When the factory returns, its own local scope normally disappears, but the returned function still holds a reference to it, so the counter stays alive. Every call to the returned function reads and updates that same counter, which is why the number climbs instead of starting again at zero.
def make_counter():
count = 0
def increment():
nonlocal count
count = count + 1
return count
return increment
counter = make_counter()
print(counter()) # 1
print(counter()) # 2
print(counter()) # 3
The keyword that makes this work is nonlocal. Without it, the line that updates the counter inside the smaller function would be treated as the creation of a brand new local variable, and Python would raise an UnboundLocalError. With it, the smaller function is explicitly allowed to rebind the name that belongs to the enclosing scope.
There are two practical points worth raising in an interview. First, a closure keeps its captured variables alive for as long as the closure object exists, so storing closures inside a long-lived list can keep a surprising amount of memory alive. Second, closures are the foundation of decorators, of callbacks, and of many functional patterns, because they let a function carry context around without needing a class for that context.