Sub topic 2
Nested functions and closures
This chapter assumes you can define and call functions, use positional and keyword arguments, and read the previous chapter on functions as objects. Closures are the mechanism that lets a decorator's wrapper remember the function it wraps.
Functions defined inside functions
Python lets you define a function inside another function. The inner function exists only while the outer function runs, unless the outer function returns it.
def make_multiplier(n):
def multiply(x):
return x * n
return multiply
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5)) # 10
print(triple(5)) # 15multiply uses n, but n is not a parameter of multiply and is not defined inside it. It belongs to make_multiplier. By the time you call double(5), make_multiplier(2) has already finished. The value 2 is still available.
What a closure is
A closure is a function bundled with the variables it uses from the enclosing scope. Python finds those variables at definition time and stores them with the function. Each call to make_multiplier creates a new multiply function with its own n, so double and triple do not interfere.
You can inspect the captured variables. They are called free variables, and Python keeps them in cells.
def make_multiplier(n):
def multiply(x):
return x * n
return multiply
double = make_multiplier(2)
print(double.__code__.co_freevars) # ('n',)
print(double.__closure__[0].cell_contents) # 2If a nested function uses no outer variables, __closure__ is None, and it is not a closure.
Changing captured variables with nonlocal
Reading an outer variable works automatically. Assigning to one does not. An assignment inside the inner function creates a new local variable instead. To rebind the outer variable, declare it with nonlocal.
def make_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
a = make_counter()
b = make_counter()
print(a(), a(), b()) # 1 2 1Without the nonlocal count line, count += 1 raises UnboundLocalError. Python sees an assignment to count, treats it as local to increment, and finds it has no value yet. Each counter keeps its own count, which is how a decorator can keep state between calls without a class.
Closures capture variables, not values
A closure remembers the variable, not the value it had when the function was created. The function reads the variable when it is called. This surprises people in loops.
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs]) # [2, 2, 2]
fixed = [lambda i=i: i for i in range(3)]
print([f() for f in fixed]) # [0, 1, 2]All three lambdas share one i, and the loop leaves it at 2. The second version uses a default argument, which is evaluated once per lambda, so each function gets its own copy. The fix usually matters in decorators that are created inside loops.
Why this matters for decorators
A decorator is a function that takes a function and returns a new one. The new function, usually called wrapper, must call the original. It can do that because the original function is a free variable captured by closure. Nothing else is needed to make decorators work.
Exercise
What does this code print, and why? Then fix it so the second call prints 2. def maketotal(): total = 0 def add(x): total += x return total return add t = maketotal() print(t(1)) print(t(1))
Show answer
The first call to t(1) raises UnboundLocalError. The assignment total += x makes total a local variable of add, and it has no value when the line runs. Adding nonlocal total as the first line of add fixes it. Then t(1) returns 1 and the second t(1) returns 2, because the closure keeps total between calls.