Sub topic 9
Enclosing Scopes and Closures
This chapter assumes you can define and call functions, read a simple traceback, and apply the LEGB lookup rule (Local, Enclosing, Global, Built-in) from earlier chapters. Here you will study the "E" in LEGB: what an enclosing scope is, how an inner function uses it, and what a closure keeps alive.
What an enclosing scope is
Python lets you define a function inside another function. The inner function's code sits inside the outer function's body. Each call to the outer function creates a local scope. The inner function can see that scope, which is called its enclosing scope.
def outer():
message = "hello from outer"
def inner():
print(message)
inner()
outer()
# Output: hello from outerinner never assigns message, so it is not a local name of inner. Python then checks the enclosing function's scope and finds it there.
Lookup follows the same order as before, with the enclosing step in the middle:
- The function's own local scope.
- The local scopes of every enclosing function, from the innermost outward.
- The global (module) scope.
- The built-in scope.
Nesting more than one level deep
Enclosing scopes can stack. Python searches them from the nearest outward and stops at the first match.
x = "global"
def outer():
x = "outer"
def middle():
def inner():
print(x)
inner()
middle()
outer()
# Output: outerinner has no x. middle has no x either, so Python continues to outer, which has one. The global x is never reached. If middle also assigned x, inner would print that value instead, because it is the nearest enclosing binding.
How Python decides a name is enclosing
Python makes this decision when it compiles the function, before any code runs. For each function, it looks at every name used in the body:
- If the function assigns the name (and has no
globalornonlocaldeclaration), the name is local to that function. - If it only reads the name, and an enclosing function assigns it, the name is a free variable: it comes from an enclosing scope.
- If no enclosing function assigns it, the name is looked up globally, then in built-ins.
You can see the result of this analysis in a function's code object:
def make_multiplier(factor):
def multiply(x):
return x * factor
return multiply
double = make_multiplier(2)
print(double.__code__.co_varnames)
print(double.__code__.co_freevars)
# Output:
# ('x',)
# ('factor',)x is local to multiply. factor is a free variable, meaning multiply uses it but an enclosing function defines it.
Closures: functions that remember
A closure is a function that keeps access to variables from an enclosing scope after that scope has finished running. In the example above, make_multiplier(2) has returned, so its call is over. Normally its local variables would disappear. But multiply still needs factor, so Python keeps that variable alive.
def make_multiplier(factor):
def multiply(x):
return x * factor
return multiply
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5))
print(triple(5))
# Output:
# 10
# 15Each call to make_multiplier creates a new local scope and a new multiply function. double remembers factor = 2 and triple remembers factor = 3. They do not interfere with each other.
Python stores each remembered variable in a cell, a small object that holds the variable's current value. A closure's __closure__ attribute is a tuple of these cells. This is mostly useful for debugging:
def make_multiplier(factor):
def multiply(x):
return x * factor
return multiply
double = make_multiplier(2)
print(double.__closure__)
print(double.__closure__[0].cell_contents)
# Output (the address will differ):
# (<cell at 0x7f1c2a3b4d00: int object at 0x7f1c2a0a1234>,)
# 2A function that has no free variables has __closure__ set to None. Module-level functions that only use globals are not closures in this sense, because globals are not stored in cells.
The cell holds the variable, not a copy of the value
The cell is shared with the enclosing function. It does not take a snapshot when the inner function is defined. The inner function reads the variable's value at the moment it is called.
def outer():
def inner():
return label
label = "set after inner was defined"
return inner()
print(outer())
# Output: set after inner was definedinner is created before label is assigned, yet the call works, because by the time inner() runs the cell holds a value. If you called inner() before the assignment, Python would raise NameError: cannot access free variable 'label' where it is not associated with a value in enclosing scope. The exact wording varies between Python versions.
This "variable, not value" behavior is the root of the loop-closure bug covered in a later chapter. For now, remember that a closure sees the variable's latest value.
Closures with changing state
Because the cell is shared, anything that modifies the object in it is visible to the closure. A list, dictionary, or set held in an enclosing variable can be mutated by the inner function:
def make_accumulator():
values = []
def add(v):
values.append(v)
return list(values)
return add
a = make_accumulator()
b = make_accumulator()
print(a(1))
print(a(2))
print(b(9))
# Output:
# [1]
# [1, 2]
# [9]add never assigns to values. It calls append on the list the name refers to. This is mutation, not rebinding, so no extra statement is needed. Each call to make_accumulator creates its own list, so a and b keep separate state.
Closures like this are a lightweight alternative to a class when you only need one function with a bit of private state.
Reading works, rebinding does not
The common error with closures comes from the rule you learned for globals. Assigning to a name anywhere in a function makes that name local to the function. This holds even when an enclosing function has a variable with the same name.
def make_counter():
count = 0
def increment():
count += 1
return count
return increment
c = make_counter()
c()
# UnboundLocalError: cannot access local variable 'count' where it is not associated with a valuecount += 1 is shorthand for count = count + 1, which assigns count. So Python marks count as local to increment. The right-hand side then reads a local count that has no value yet. The enclosing count = 0 is never consulted.
The fix is the nonlocal statement, the subject of the next chapter. Until then, two alternatives work with what you already know: mutate a container (as make_accumulator does) or use a different local name for the new value.
The table summarizes what each operation inside an inner function does to an enclosing variable.
| Operation in the inner function | Example | Effect on the enclosing variable |
|---|---|---|
| Read | `return factor` | Works. Finds the enclosing binding. |
| Mutate the object | `values.append(v)` | Works. The name is not rebound. |
| Rebind with assignment | `count = 5` or `count += 1` | Creates a new local name. The enclosing variable is unchanged, or you get `UnboundLocalError`. |
Closure versus global state
You could write the accumulator with a module-level list instead. Closures have practical advantages:
- Each closure instance has its own state, while a global is shared by everything.
- The state cannot be reached or changed by name from outside, so other code cannot touch it by accident.
- Nothing is added to the module namespace.
The cost is that the state is harder to inspect. You cannot easily print it without going through __closure__. If you need to inspect or reset the state, a class with attributes is usually clearer.
Key points
- An enclosing scope is the local scope of a function that contains another function's definition.
- Python resolves names at compile time. A name assigned in a function is local to it. A name only read, but assigned in an enclosing function, is a free variable.
- A closure is an inner function plus the cells for its free variables. The cells survive after the outer function returns.
- Each call to the outer function creates new cells, so separate closures keep separate state.
- Inner functions can read enclosing variables and mutate the objects they refer to. Rebinding needs
nonlocal, which the next chapter covers.
Exercise
What does the following code print, and why? def outer(): items = [] def add(x): items.append(x) def total(): return len(items) add("a") add("b") return total t = outer() print(t())
Show answer
It prints 2. Both add and total have items as a free variable, so they share the same cell from the single call to outer(). add mutates the list without rebinding the name items, so no nonlocal is needed. When outer returns total, the cell stays alive, and t() reports the length of the list that add filled.
Exercise
This function raises UnboundLocalError when you call the returned function. Which line causes the problem, and how can you fix it without using nonlocal? def make_total(): total = 0 def add(n): total = total + n return total return add
Show answer
The line total = total + n assigns total, so Python treats total as local to add, and the right-hand side reads it before it has a value. One fix is to keep the running total in a mutable container, for example total = [0] in make_total, then write total[0] += n inside add and return total[0]. This mutates the list instead of rebinding the name total.