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 basic lambda. You should also know how local variables work inside a function.
What a closure is
A closure is a function that keeps access to variables from the scope where it was defined, even after that scope has finished running. The variables a closure keeps are called free variables. They are not local to the inner function and not global. They belong to an enclosing function.
def make_multiplier(factor):
return lambda x: x * factor
double = make_multiplier(2)
print(double(5)) # 10When make_multiplier(2) returns, its local variable factor would normally disappear. The returned lambda still uses factor, so Python keeps it alive. The lambda double is a closure over factor.
How Python stores the captured variable
Python does not copy the value into the inner function. It keeps a reference to a cell object that holds the variable. You can see these cells on the function itself.
def make_multiplier(factor):
return lambda x: x * factor
triple = make_multiplier(3)
print(triple.__code__.co_freevars) # ('factor',)
print(triple.__closure__[0].cell_contents) # 3co_freevars lists the names of the captured variables. __closure__ holds one cell for each of them. Every call to make_multiplier creates a new cell, so double and triple do not affect each other.
Closures see changes to the variable
Because the closure holds the variable and not a snapshot of its value, later changes are visible to it. The next example uses a nested def with a counter.
def make_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
counter = make_counter()
print(counter()) # 1
print(counter()) # 2
print(counter()) # 3The nonlocal statement tells Python that count refers to the variable in the enclosing function. Without it, count += 1 would try to create a new local variable and raise UnboundLocalError. Reading a captured variable needs no declaration. Rebinding it does.
A lambda cannot contain a statement such as nonlocal or an assignment. If a closure needs to rebind a captured variable, use def.
Common errors
- Forgetting
nonlocal. Assigning to a captured name inside the inner function creates a local variable. Python then raisesUnboundLocalErrorif you read it before the assignment. - Expecting a snapshot. If the outer variable changes after the closure is created, the closure sees the new value. The next chapter shows how this causes a bug when you create lambdas in a loop.
- Using
globalinstead ofnonlocal.globalrefers to module-level names. For a variable in an enclosing function, usenonlocal. - Sharing mutable state by accident. If you capture a list or dictionary, every closure that captured it shares the same object.
def make_logger():
messages = []
def log(text):
messages.append(text) # mutation, so no nonlocal is needed
return len(messages)
return log
log = make_logger()
print(log("start")) # 1
print(log("stop")) # 2Here messages.append changes the list in place and does not rebind the name, so nonlocal is not needed.
Summary
A closure pairs a function with the variables it uses from its enclosing scope. Python stores those variables in cells, and the closure sees later changes to them. Use nonlocal to rebind a captured name, and use def when you need it.
Exercise
What does this code print, and why? def outer(): then x = 1, then def inner(): return x, then x = 2, then return inner. After that, print(outer()()).
Show answer
It prints 2. The inner function captures the variable x, not the value 1. When inner is finally called, x has already been rebound to 2, so inner returns 2.
Exercise
Write a function 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 total.
Show answer
def makeaccumulator(start): total = start def add(n): nonlocal total total += n return total return add acc = makeaccumulator(10) print(acc(5)) # 15 print(acc(2)) # 17