Sub topic 8
Closures: functions that remember their surroundings
This chapter assumes you can define functions with def, pass functions as arguments, and write a lambda. It also assumes you know default arguments and *args/**kwargs. A closure builds on those pieces. It is a function that keeps access to variables from the place where it was created, even after that place has finished running.
What a closure is
A function defined inside another function can read the outer function's local variables. When the inner function is returned or stored, it carries those variables with it. That combination of function plus remembered variables is a closure.
def make_multiplier(factor):
return lambda x: x * factor
double = make_multiplier(2)
print(double(5)) # 10When make_multiplier(2) returns, its local scope would normally be discarded. The lambda still uses factor, so Python keeps that variable alive. Calling double(5) finds factor as 2.
Three things must be true for a closure to exist:
- A function is defined inside another function.
- The inner function uses a variable from the outer function's scope.
- The inner function outlives the call that created it, for example because it is returned or stored.
A function that merely uses a global variable is not a closure. Globals are found through the module namespace, not through captured cells.
How Python implements it
Python does not copy the value of the captured variable. It stores a reference to a small container called a cell. Both the outer function and the inner function point to the same cell. You can see this on the function object.
def make_multiplier(factor):
def multiply(x):
return x * factor
return multiply
double = make_multiplier(2)
print(double.__code__.co_freevars) # ('factor',)
print(double.__closure__[0].cell_contents) # 2__code__.co_freevarslists the names the function uses but does not define itself. These are called free variables.__closure__is a tuple of cells, one per free variable, in the same order.cell_contentsis the value currently stored in a cell.
A function with no free variables has __closure__ set to None.
def plain(x):
return x + 1
print(plain.__closure__) # NoneEach call to the outer function creates new cells. Closures made by separate calls do not share state.
triple = make_multiplier(3)
print(double(10), triple(10)) # 20 30Closures see the variable, not a snapshot
Because the closure holds a reference to the cell, it sees later changes to the variable. This is the most common source of surprise with closures.
def demo():
message = "first"
def show():
return message
message = "second"
return show
print(demo()()) # secondThe function show is created while message is "first". By the time it is called, the cell holds "second", and that is what it returns. The next chapter covers how this behavior causes a bug when lambdas are created in a loop. For now, remember the rule: a closure remembers the variable, not the value the variable had at creation time.
Closures that change state: nonlocal
A closure can read a free variable without any special syntax. Assigning to it is different. An assignment inside a function creates a new local variable by default, so the outer variable is not changed.
def make_counter_broken():
count = 0
def increment():
count += 1 # UnboundLocalError when called
return count
return increment
counter = make_counter_broken()
try:
counter()
except UnboundLocalError as err:
print("error:", err)Python sees count += 1, decides count is local to increment, and then fails because that local has no value yet. The nonlocal statement tells Python that the name refers to the nearest enclosing function's variable.
def make_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
a = make_counter()
b = make_counter()
print(a(), a(), a()) # 1 2 3
print(b()) # 1Each counter has its own count cell, so a and b are independent. The closure has become a small object with private state, and no class was needed.
nonlocal only works for names in an enclosing function. It cannot refer to globals (use global for those), and the name must already exist in an enclosing scope.
Mutating versus rebinding
nonlocal is needed only when you rebind the name, meaning you make it point at a different object. If the captured object is mutable, you can change it in place without nonlocal.
def make_log():
entries = []
def add(item):
entries.append(item) # mutation, no nonlocal needed
return len(entries)
return add
log = make_log()
print(log("a"), log("b")) # 1 2Here entries.append(...) modifies the list that the cell points to. The name entries is never assigned inside add, so Python treats it as a free variable.
Be careful with entries += [item]. For a list, += mutates in place but is still an assignment to the name, so Python treats entries as local and raises UnboundLocalError unless you declare it nonlocal.
Lambdas are closures too
A lambda is a function, so it captures variables the same way a def function does. The make_multiplier lambda above is a closure. The difference is only in what you can express. A lambda holds a single expression, so it cannot contain nonlocal or an assignment statement.
def make_adder(n):
return lambda x: x + n
add10 = make_adder(10)
print(add10(5)) # 15If a closure needs to update captured state, use def with nonlocal.
Closures compared with classes
A closure with state does the same job as a small class with one method. The choice is mostly about how much behavior and visibility you need.
| Need | Closure | Class |
|---|---|---|
| One operation with a little private state | Short and direct | More code than needed |
| Several related operations on shared state | Awkward | Natural |
| Inspecting state from outside | Possible only through `__closure__` | Ordinary attributes |
| Copying or serializing with pickle | Not supported for inner functions | Supported |
| Subclassing or extending | Not possible | Supported |
The pickle limit matters in practice. Functions defined inside other functions cannot be pickled, so they cannot be sent to worker processes with multiprocessing. A module-level function or a class instance works instead.
Common errors
- Expecting a snapshot. A closure sees the current value of the variable. If the variable changes after the closure is created, the closure sees the change.
- Assigning without
nonlocal. Any assignment to a name inside the inner function makes it local. Reading before that assignment raisesUnboundLocalError. - Using
globalinstead ofnonlocal.global countwould refer to a module-levelcount, not the enclosing function's variable. - Holding references longer than intended. A closure keeps its cells alive. If a cell holds a large object, that object stays in memory as long as the closure exists.
- Shared state by accident. Two functions created inside the same outer call share the same cells. This can be useful and also surprising.
def make_pair():
value = 0
def get():
return value
def set_(v):
nonlocal value
value = v
return get, set_
get, set_ = make_pair()
set_(42)
print(get()) # 42Here get and set_ were created in one call, so they share one value cell. This is the intended design, but it is the same mechanism that causes late-binding bugs when you did not intend sharing.
Inspecting closures while debugging
When a function behaves oddly, check what it captured.
def make_greeter(greeting, punctuation="!"):
def greet(name):
return f"{greeting}, {name}{punctuation}"
return greet
hello = make_greeter("Hello")
names = hello.__code__.co_freevars
values = [cell.cell_contents for cell in hello.__closure__]
print(dict(zip(names, values)))
# {'greeting': 'Hello', 'punctuation': '!'}Free variables and cells are listed in the same order, so zip pairs them correctly. This is a debugging aid, not an interface to build programs on.
Exercise
Write make_accumulator(start) that returns a function. Each call to the returned function takes a number, adds it to a running total that begins at start, and returns the new total. Two accumulators must not share their totals. Then say why the returned function needs nonlocal.
Show answer
def makeaccumulator(start): total = start def add(n): nonlocal total total += n return total return add acc = makeaccumulator(10) other = makeaccumulator(0) print(acc(5), acc(5), other(1)) # 15 20 1 The statement total += n is an assignment, so without nonlocal Python treats total as a local variable of add and raises UnboundLocalError. With nonlocal, the name refers to the cell in makeaccumulator. Each call to make_accumulator creates a new cell, so the two accumulators stay independent.
Exercise
What does this code print, and why? def build(): x = 1 f = lambda: x x = 2 return f print(build()())
Show answer
It prints 2. The lambda captures the variable x, not the value 1. When the lambda is called, the cell for x holds 2, because x was reassigned before build returned.