I. What Is a Closure
A closure is when a function object can remember and access the free variables in the outer scope where it was defined. Even after the outer function has finished executing, these variables can still be accessed by the inner function.
To understand closures, you first need to grasp three concepts:
- Nested function: a function defined inside another function.
- Free variable: a variable that is not defined in the current function but exists in an outer scope.
- Closure: an inner function references a free variable in an outer scope and can still access that variable after the outer function has finished executing.
The simplest closure example:
def outer():
message = "Hello, Closure"
def inner():
print(message)
return inner
func = outer()
func()
Output:
Hello, Closure
In this code:
outer()defines an outer function.inner()is a nested function defined insideouter().messageis defined inouter(), but not ininner().inner()referencesmessage, somessageis a free variable forinner().outer()returns theinnerfunction object.- Even though
outer()has finished executing,func()can still accessmessage.
The most important point here is not function nesting itself, but that the inner function retains the ability to access the outer variable.
II. The Concept of Free Variables
A free variable is a variable defined relative to the current function.
If a variable is not defined in the current function's local scope but is defined in an outer function's scope and is referenced by the current function, then it is a free variable of the current function.
For example:
def outer():
name = "Python"
def inner():
age = 30
print(name)
print(age)
return inner
In inner():
| Variable | Definition location | Role for inner |
|---|---|---|
name |
Outer function | Free variable |
age |
Current function | Local variable |
print |
Built-in namespace | Built-in name within global lookup scope |
The main differences between free variables and local variables:
- Local variables are defined or bound by the current function.
- Free variables are provided by an outer scope; the current function only references them.
- Free variables usually retain access to the outer binding through the closure mechanism.
2.1 Free Variables and the LEGB Rule
Python uses the LEGB rule to look up names:
| Level | Meaning | Description |
|---|---|---|
| L | Local | Current function's local scope |
| E | Enclosing | Outer nested function scope |
| G | Global | Module global scope |
| B | Built-in | Built-in namespace |
For nested functions, free variables usually come from the Enclosing scope.
language = "Global Python"
def outer():
language = "Enclosing Python"
def inner():
print(language)
return inner
func = outer()
func()
Output:
Enclosing Python
inner() first looks for language in its own local scope. When it does not find it, it continues searching in the outer function scope and finally finds the variable in outer().
2.2 Free Variables Are Not the Same as Global Variables
Free variables and global variables are both not local variables of the current function, but they come from different sources.
global_name = "Global"
def outer():
enclosing_name = "Enclosing"
def inner():
print(global_name)
print(enclosing_name)
return inner
Here:
global_namecomes from the module's global scope.enclosing_namecomes from the outer function's scope.enclosing_nameis a free variable ofinner().global_nameis not a closure free variable ofinner().
Therefore, not every external name accessed by an inner function should be called a closure variable.
III. How Closures Are Formed
A closure is usually formed through three steps:
- Define an outer function and create variables inside it.
- Define an inner function and reference the outer variables.
- Return or save the inner function as an object so that it can continue to be used after the outer function finishes executing.
The following flowchart illustrates this:
flowchart TD
A["Call outer function outer"] --> B["Create outer local variable"]
B --> C["Define inner function inner"]
C --> D["inner references outer variable"]
D --> E["Form a free variable relationship"]
E --> F["Return inner function object"]
F --> G["Outer function finishes executing"]
G --> H["Inner function can still access the free variable"]
H --> I["Call inner function"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style H fill:#FFF5DE,stroke:#E8D29A,color:#334155
style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Note: merely defining a nested function does not necessarily mean a closure is formed. The inner function must actually reference a variable in the outer function's scope for the corresponding free variable relationship to form.
3.1 Why Variables Do Not Disappear After the Outer Function Finishes
Normally, after a function call ends, its local names are no longer in an active local scope.
However, outer variables referenced by a closure do not immediately become invalid just because the outer function returns.
Python uses closure-related mechanisms to retain the bindings needed to access these variables.
For example:
def make_counter():
count = 0
def counter():
print(count)
return counter
counter = make_counter()
counter()
counter()
Output:
0
0
Even though make_counter() has finished executing, counter() can still read the original count.
What is retained here is the object corresponding to the variable binding and the access relationship to it, not simply a copy of the variable's value placed into the inner function.
IV. The Variable Binding Mechanism of Closures
The most important point in understanding closures is that a closure captures variable bindings, not a fixed snapshot of the variables at the time the closure is defined.
This means that the closure can observe subsequent changes to the free variable.
def outer():
message = "初始值"
def inner():
print(message)
message = "修改后的值"
return inner
func = outer()
func()
Output:
修改后的值
Although the value of message was "初始值" when inner() was defined, the outer function had already changed it to "修改后的值" before inner() was called.
Therefore, the closure accesses the variable binding in the outer scope, not a value copied when the inner function was created.
4.1 The Difference Between Closures and Ordinary Variable Copying
Compare the following two cases:
def make_closure():
value = 10
def inner():
return value
value = 20
return inner
def make_snapshot():
value = 10
def inner(value=value):
return value
value = 20
return inner
closure = make_closure()
snapshot = make_snapshot()
print(closure())
print(snapshot())
Output:
20
10
The difference between the two approaches:
| Approach | How the variable is obtained | Result |
|---|---|---|
| Regular closure | Accesses the outer variable binding | 20 |
| Default parameter capture | Default parameter evaluated when the function is defined | 10 |
Default parameters are evaluated when the function is defined, so they can be used to preserve the value at that time.
However, default parameter capture and closure capture are not the same mechanism.
V. Using nonlocal to Modify Closure Variables
A closure can not only read outer variables but also modify variable bindings in the outer function's scope via nonlocal.
For example, create a counter:
def make_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
counter = make_counter()
print(counter())
print(counter())
print(counter())
Output:
1
2
3
The key here is:
nonlocal count
It tells Python that count in counter() is not a new local variable but is bound to the existing count in the nearest enclosing function scope.
If nonlocal is not used:
def make_counter():
count = 0
def counter():
count += 1
return count
return counter
counter = make_counter()
counter()
Execution produces:
UnboundLocalError
The reason is that because the function body contains an assignment to count, Python treats it as a local variable of the current function. But when count += 1 is executed, the local variable has not yet been initialized.
5.1 Differences Between global and nonlocal
| Comparison dimension | global | nonlocal |
|---|---|---|
| Scope | Module global scope | Enclosing function scope |
| Lookup location | Module global namespace | Nearest enclosing function scope |
| Requires an existing binding | Not required to exist beforehand | Must exist |
| Common use | Modify module-level variable bindings | Modify closure variable bindings |
Example:
count = 100
def outer():
value = 10
def inner():
global count
nonlocal value
count += 1
value += 1
print(count, value)
return inner
func = outer()
func()
func()
Output:
101 11
102 12
Note:
nonlocalcannot be used to reference module global variables.nonlocalcan only reference names that already exist in an enclosing function scope.- The namespace of a class body does not become the ordinary enclosing function scope of its methods.
5.2 The Difference Between Modifying an Object and Rebinding a Variable
If a closure variable points to a mutable object, its internal state can be modified even without using nonlocal.
def make_list():
items = []
def add_item(value):
items.append(value)
return items
return add_item
add = make_list()
print(add("Python"))
print(add("Closure"))
Output:
['Python']
['Python', 'Closure']
Here, append() modifies the list object itself and does not rebind the name items, so nonlocal is not needed.
If you assign a new value to items, then you need to use nonlocal:
def make_list():
items = []
def replace_items():
nonlocal items
items = ["Python", "Closure"]
return replace_items
This is a very important distinction when understanding modification of closure variables:
- Modifying the internal state of an object does not necessarily require
nonlocal. - Rebinding an outer variable requires
nonlocal.
6. How Python Stores Closure Information
Python function objects provide some attributes that can be used to inspect the structure of closures.
The most common ones are:
__closure__: a tuple holding the closure cells.__code__.co_freevars: records the names of free variables referenced by the function.
Example:
def outer():
language = "Python"
version = 3
def inner():
return language, version
return inner
func = outer()
print(func.__code__.co_freevars)
print(func.__closure__)
Possible output:
('language', 'version')
(<cell at ...>, <cell at ...>)
The exact content displayed for the cells depends on the runtime environment.
6.1 co_freevars
co_freevars is an attribute of the code object, used to record the names of the free variables used by the function.
def outer():
name = "Python"
def inner():
return name
return inner
func = outer()
print(func.__code__.co_freevars)
Output:
('name',)
It can help developers determine which outer free variables a function references.
6.2 closure
__closure__ is an attribute of the function object.
When a function has free variables, it usually contains the corresponding cell objects.
def outer():
message = "Hello"
def inner():
return message
return inner
func = outer()
for cell in func.__closure__:
print(cell.cell_contents)
Output:
Hello
Here:
__closure__stores the closure cells.cell_contentscan read the object currently referenced by the cell.- A cell carries a variable binding, not a simple snapshot of a fixed value.
These attributes are useful for debugging, learning, and understanding how closures work internally; it is not recommended to rely on their internal structure in ordinary application code.
6.3 Sharing of Closure Variables
If multiple inner functions reference the same outer variable, they can share the same closure binding.
def outer():
count = 0
def increment():
nonlocal count
count += 1
return count
def get_count():
return count
return increment, get_count
increment, get_count = outer()
print(increment())
print(increment())
print(get_count())
Output:
1
2
2
Both inner functions access count inside outer(), so the changes made by increment() can be observed by get_count().
Conceptually:
flowchart TD
A["outer creates count"] --> B["Shared closure binding"]
B --> C["increment function"]
B --> D["get_count function"]
C --> E["Modify count"]
E --> F["count updated"]
F --> G["get_count reads the latest value"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
7. Closures and Late Binding of Loop Variables
A very common issue with closures in loops is late binding of free variables (Late Binding).
Consider the following code:
def create_functions():
functions = []
for i in range(3):
functions.append(lambda: i)
return functions
funcs = create_functions()
print(funcs[0]())
print(funcs[1]())
print(funcs[2]())
Output:
2
2
2
Many beginners might expect the output to be:
0
1
2
But that is not what actually happens.
The reason is:
- Each iteration of the loop updates the variable
i. - All three lambda functions reference the same outer variable
i. - When the lambda functions are created, the value of
iis not copied immediately. - After the loop ends, the value of
iis2. - When the three functions are called, they all read the current
i.
7.1 Solving Late Binding with Default Arguments
A common solution is to use a default argument to capture the current loop value:
def create_functions():
functions = []
for i in range(3):
functions.append(lambda i=i: i)
return functions
funcs = create_functions()
print(funcs[0]())
print(funcs[1]())
print(funcs[2]())
Output:
0
1
2
Here, i=i means:
- The
ion the left is a function parameter. - The
ion the right is the variable from the outer scope when the lambda function is created. - Default arguments are evaluated when the function is defined.
Each lambda function retains the default argument value that was in effect when it was created.
7.2 Using Factory Functions to Create Independent Closures
You can also create an independent outer scope for each loop iteration through an extra function call:
def make_function(value):
def inner():
return value
return inner
def create_functions():
functions = []
for i in range(3):
functions.append(make_function(i))
return functions
funcs = create_functions()
print([func() for func in funcs])
Output:
[0, 1, 2]
Each call to make_function() creates an independent function-call environment, so each closure has its own value binding.
7.3 How to Choose Between the Two Approaches
| Approach | Implementation | Use case |
|---|---|---|
| Default argument capture | lambda i=i: i |
Capturing simple values |
| Factory function | Provides a separate scope for each function created | Complex closure logic |
| functools.partial | Binds function arguments in advance | Fixing some of the call arguments |
For simple loop callbacks, default arguments are usually the most straightforward; for closures containing complex logic or multiple states, factory functions are easier to maintain.
VIII. Typical Application Scenarios of Closures
Closures are not only a language feature but also a common design technique in Python engineering.
8.1 Data Encapsulation and Private State
Python does not, as some object-oriented languages do, mandate that all private members be implemented through a specific access-control mechanism.
By hiding outer variables, closures can provide external code with a limited set of operations.
def create_account(initial_balance):
balance = initial_balance
def deposit(amount):
nonlocal balance
if amount <= 0:
raise ValueError("金额必须大于零")
balance += amount
return balance
def get_balance():
return balance
return deposit, get_balance
deposit, get_balance = create_account(1000)
deposit(500)
print(get_balance())