Sub topic 2
Nested functions and closures
A decorator is a function that builds and returns another function. That only works because of two language features: functions can be defined inside other functions, and an inner function can keep using the variables of the function that created it. This chapter covers both. Later chapters build decorators on top of them.
This chapter assumes you can define and call functions, know that functions are objects you can pass around and return, and understand local variables and function arguments.
Defining a function inside a function
A def statement can appear anywhere, including inside another function body. The inner function is created each time the outer function runs, and its name is local to the outer function.
def outer():
message = "hello"
def inner():
print(message)
inner()
outer() # helloinner does not receive message as a parameter and does not define it. Python finds it by searching the enclosing function's scope. Outside outer, the name inner does not exist, so calling inner() there raises NameError.
How Python looks up names
When Python meets a name inside a function, it searches four scopes in order. The order is known as LEGB.
| Scope | Meaning | Example |
|---|---|---|
| Local | Names assigned in the current function | parameters, local variables |
| Enclosing | Names in any outer function that contains this one | `message` inside `inner` above |
| Global | Names at module level | imported modules, top-level functions |
| Built-in | Names Python provides | `len`, `print`, `range` |
The search stops at the first scope that has the name. The enclosing scope is the one that matters here. A name that an inner function reads from an enclosing function is called a free variable.
What makes it a closure
So far the inner function ran while the outer function was still active. The interesting case is when the outer function has already returned.
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)) # 15By the time double(5) runs, the call make_multiplier(2) is finished. Normally its local variable n would be gone. It is not, because multiply still refers to it. Python keeps n alive and attaches it to the function object. A function bundled with the variables it uses from enclosing scopes is a closure.
Each call to make_multiplier creates a new n and a new multiply. That is why double and triple do not interfere with each other.
Correction: the diagram must be in the required fence format. Here it is.
Inspecting a closure
Python exposes the captured variables, so you can check this instead of taking it on trust.
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__) # (<cell at 0x...: int object at 0x...>,)
print(double.__closure__[0].cell_contents) # 2co_freevars lists the names of the free variables. __closure__ is a tuple of cells, one per free variable, in the same order. A cell is a small box that holds a value. A function with no free variables has __closure__ set to None. This is a quick way to tell whether a function is really a closure.
Closures capture variables, not values. The cell holds a reference to the variable, so if the variable changes later, the closure sees the new value. The loop example later in this chapter relies on this.
Closures can hold state
Because the captured variable lives as long as the function does, a closure can act as a small object with private state. A counter is the usual example.
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()) # 1a and b each have their own count. Nothing outside the closure can reach count by name.
Why nonlocal is needed
Reading a free variable needs no special syntax. Assigning to it does. Without nonlocal, the line count += 1 would make count a local variable of increment, because any assignment inside a function creates a local name. Python would then try to read that local before it has a value.
def broken_counter():
count = 0
def increment():
count += 1 # no nonlocal
return count
return increment
c = broken_counter()
c() # UnboundLocalError: cannot access local variable 'count' ...The nonlocal statement tells Python that count refers to the nearest enclosing function's variable. It is different from global, which refers to a module-level name. nonlocal only works if the name already exists in an enclosing function. Otherwise you get a SyntaxError.
Mutating an object does not count as assignment. If the captured variable is a list or dictionary, you can change its contents with no nonlocal:
def make_log():
entries = []
def add(item):
entries.append(item) # mutation, not assignment
return len(entries)
return addOnly rebinding the name needs nonlocal. Rebinding includes += on an integer, string or tuple, because those types are immutable and += creates a new object.
A common trap: late binding
Closures capture variables, not the values the variables had at definition time. This surprises many people when functions are created in a loop.
funcs = []
for i in range(3):
funcs.append(lambda: i)
print([f() for f in funcs]) # [2, 2, 2]The three lambdas all share one variable, i. The loop ends with i equal to 2, and the lambdas look up i only when they are called. This behavior is called late binding.
There are two common fixes. The first is a default argument, which is evaluated when the function is defined:
funcs = [lambda i=i: i for i in range(3)]
print([f() for f in funcs]) # [0, 1, 2]The second is a factory function, which gives each closure its own variable. This is the same shape as make_multiplier:
def make_getter(value):
return lambda: value
funcs = [make_getter(i) for i in range(3)]
print([f() for f in funcs]) # [0, 1, 2]The default-argument trick changes the function's signature, since callers could pass an extra argument. The factory keeps the signature clean, so it is usually the better choice.
Why this matters for decorators
Here is the shape of nearly every decorator, in outline:
def decorator(func):
def wrapper():
print("before")
result = func() # func is a free variable
print("after")
return result
return wrapperwrapper uses func, which belongs to decorator. After decorator returns, wrapper still holds func in its closure. That is how the wrapper can call the original function later. Without closures, a decorator would have no way to remember which function it wraps.
You can see this directly:
def decorator(func):
def wrapper():
return func()
return wrapper
def hello():
return "hello"
wrapped = decorator(hello)
print(wrapped.__closure__[0].cell_contents is hello) # TrueThe closure cell holds the original function itself.
Edge cases and gotchas
- Memory stays alive. A closure keeps its captured variables alive as long as the closure exists. If a closure captures a large object, that object is not freed. Capture only what you need.
- Only used names are captured. Python creates a cell for a name only if the inner function actually refers to it. An unused outer variable is not in
__closure__. - Parameters count as enclosing variables. In
make_multiplier,nis a parameter of the outer function, and it is captured exactly like a local variable. - Nesting can go deeper. A function inside a function inside a function can read variables from every level.
nonlocalbinds to the nearest enclosing scope that has the name. Decorator factories, which come later, use three levels. - Redefinition is not capture. If the inner function assigns to a name, that name is local to it, even if an outer function has the same name. This is the cause of the
UnboundLocalErrorabove.
Summary of the working model
- An inner function is created each time the outer function runs.
- Names the inner function uses but does not define are looked up in enclosing function scopes.
- If the inner function outlives the outer call, Python stores those variables in cells and attaches them to the function as
__closure__. - Reading a captured variable needs no extra syntax. Rebinding it requires
nonlocal. - Closures capture variables, not values, so later changes are visible.
Exercise
What does this code print, and why? def makeaccumulator(): total = 0 def add(x): total += x return total return add acc = makeaccumulator() print(acc(5)) How do you fix it, and what would acc(5) then print on a second call?
Show answer
It raises UnboundLocalError. The statement total += x assigns to total, so Python treats total as a local variable of add, and reading it before assignment fails. Fix it by adding "nonlocal total" as the first line of add. After the fix, the first call prints 5 and a second call acc(5) returns 10, because the closure keeps total between calls.
Exercise
The code below is meant to print 0, 1, 2 but prints 2, 2, 2. Explain why, then rewrite the second line using a default argument so it prints 0, 1, 2. callbacks = [lambda: n for n in range(3)] print([cb() for cb in callbacks])
Show answer
All three lambdas share the single variable n and look it up when called, after the loop has finished with n equal to 2 (late binding). The fix is: callbacks = [lambda n=n: n for n in range(3)]. The default value n=n is evaluated at definition time, so each lambda stores its own number. The output is [0, 1, 2].