Sub topic 9
Enclosing Scopes and Closures
This chapter assumes you can define and call functions, and that you know the LEGB lookup order (Local, Enclosing, Global, Built-in) and why assignment makes a name local. Here we look at the "E" in LEGB.
What an enclosing scope is
Python lets you define a function inside another function. The inner function can use names that belong to the outer function. Those names live in the outer function's local scope. From the inner function's point of view, that scope is the enclosing scope.
def outer():
message = "hello from outer"
def inner():
print(message)
inner()
outer()
# Output: hello from outerInside inner, Python looks for message in this order:
inner's own local scope. It is not there.outer's scope, the enclosing scope. It is found here.
If the name were not in outer either, Python would continue to the global scope and then the built-ins.
Closures
A closure is an inner function that keeps access to names from its enclosing scope, even after the outer function has returned. Normally a function's local names disappear when it returns. Names that an inner function still uses are kept 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
# 15make_multiplier has finished running by the time double(5) is called. Yet double still knows that factor is 2. Each call to make_multiplier creates a new enclosing scope, so double and triple have separate copies of factor.
Looking inside a closure
Python records which names a function takes from an enclosing scope. These are called free variables. You can inspect them:
def make_multiplier(factor):
def multiply(x):
return x * factor
return multiply
double = make_multiplier(2)
print(double.__code__.co_freevars)
print(double.__closure__[0].cell_contents)
# Output:
# ('factor',)
# 2The values are stored in cells. A cell is a small container that the enclosing function and the inner function both point to. This detail matters: a closure holds a reference to the variable itself, not a snapshot of its value at the time the inner function was defined.
Lookup works across several levels
Python checks each enclosing function from the innermost outward and stops at the first match.
def level_one():
name = "one"
def level_two():
def level_three():
return name
return level_three()
return level_two()
print(level_one())
# Output: oneIf two enclosing functions both define name, the nearest one wins.
Reading works, rebinding does not (yet)
Reading an enclosing name needs no special syntax. Assigning to it does. The rule from earlier chapters still applies: assigning to a name inside a function makes it local to that function.
def make_counter():
total = 0
def add(n):
total += n
return total
return add
counter = make_counter()
counter(2)
# UnboundLocalError: cannot access local variable 'total' where it is not associated with a valueBecause total += n assigns to total, Python treats total as local to add. The read happens before any local value exists, so the call fails. The next chapter shows how the nonlocal statement fixes this.
Common errors
- Expecting an inner function to see names from a function that merely called it. Scope follows where the code is written, not where it is called.
- Assigning to an enclosing name and getting
UnboundLocalError. - Forgetting that each call to the outer function creates a new, independent set of enclosing variables.
Exercise
What does this code print, and why? def outer(): x = "enclosing" def inner(): return x return inner x = "global" print(outer()())
Show answer
It prints "enclosing". Inside inner, Python searches the local scope first, then the enclosing scope of outer, where x is "enclosing". The global x is never reached because the enclosing scope is searched before the global scope.