- Courses
- 💻Programming Languages
- 🐍Python
- Functional Programming
- Closures
On this page
Closures in Python: A Functional Programming Deep Dive
Published on July 6, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
A closure is a function that remembers the environment in which it was created — even after that environment has ceased to exist. In Python, closures are formed when a nested function references variables from its enclosing (outer) function, and that outer function returns the nested function. The nested function “closes over” the data, maintaining a reference to it and preserving access to those variables long after the outer function has finished executing. This seemingly simple mechanism is one of the most powerful tools in functional programming: closures enable stateful functions without classes, function factories that generate customised behaviour, and the decorator pattern that underpins much of Python's modern framework ecosystem. This lesson explores how closures work in Python, how to create them, when to use them, and the common pitfalls to avoid.
What Is a Closure?
A closure is a function object that remembers values in enclosing scopes even if they are not present in memory. Think of a closure as a function plus an extra environment that holds the values of variables that it depends on. This environment persists even after the outer function has returned.
In simpler terms, a closure “closes over” the free variables from its enclosing scope, preserving access to them. The data is stored in what is called the function's cell and remains accessible even after the outer function has finished executing.
def outer_function(x):
def inner_function(y):
return x + y
return inner_function
add_five = outer_function(5)
print(add_five(3)) # Output: 8
In this example, outer_function takes x and defines inner_function that uses x. When outer_function(5) is called, it returns inner_function with x fixed at 5. The returned function — the closure — remembers x = 5 even after outer_function has finished executing.
Three Conditions for a Closure
A closure is created in Python when three conditions are met:
- A nested function is defined inside an outer function — the inner function exists within the lexical scope of the outer function.
- The inner function references variables from the outer function — these are called “free variables” because they are not defined in the inner function's own scope.
- The outer function returns the inner function — returning the nested function allows it to be used outside the outer function's scope.
When these conditions are satisfied, Python creates a closure. The inner function retains access to the outer function's variables even after the outer function has completed execution.
How Closures Work Internally
When Python creates a closure, it stores the outer function's variables in a special attribute called __closure__. The inner function keeps a reference — not a copy — to these variables.
def make_multiplier(factor):
def multiply_by(x):
return x * factor
return multiply_by
double = make_multiplier(2)
print(double(5)) # Output: 10
# Inspect the closure
print(double.__closure__) # (<cell at 0x...: int object at 0x...>,)
print(double.__closure__[0].cell_contents) # 2
The __closure__ attribute returns a tuple of cell objects, and each cell's cell_contents attribute reveals the captured value. This demonstrates that the closure holds a reference to the variable itself, not a snapshot of its value at the time of creation.
Capturing Mutable Variables
Crucially, closures capture variables by reference, not by value. This means if the captured variable changes, the closure sees the updated value:
def create_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
c = create_counter()
print(c()) # 1
print(c()) # 2
print(c()) # 3
The nonlocal keyword is required to modify the captured variable from within the inner function. Without nonlocal, Python treats count as a local variable in the inner function, leading to an UnboundLocalError.
Closures vs. Classes
Closures and classes are both ways to encapsulate state and behaviour. The choice between them depends on the complexity of the task.
When to Use Closures
Closures are an elegant solution for simple cases with one or a few methods. They avoid the overhead of class definitions and can be more concise:
# Using a closure
def make_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
# Using a class
class Counter:
def __init__(self):
self.count = 0
def __call__(self):
self.count += 1
return self.count
When to Use Classes
For larger cases with multiple attributes and methods, a class implementation is more appropriate. Classes provide clearer organisation, inheritance, and better readability for complex state management.
Practical Examples of Closures
Example 1: Function Factories
Closures are ideal for creating function factories — functions that generate other functions with customised behaviour:
def make_multiplier(factor):
def multiplier(x):
return x * factor
return multiplier
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5)) # 10
print(triple(5)) # 15
Each call to make_multiplier creates a new closure with its own captured factor value.
Example 2: Maintaining State
Closures can maintain state across multiple calls without using global variables:
def make_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
counter1 = make_counter()
counter2 = make_counter()
print(counter1()) # 1
print(counter1()) # 2
print(counter2()) # 1 — independent state
Each closure maintains its own independent state.
Example 3: String Formatting
Closures can capture configuration data for later use:
def prefixer(prefix):
def add_prefix(text):
return f"{prefix} {text}"
return add_prefix
hello = prefixer("Hello")
print(hello("World")) # Hello World
print(hello("Python")) # Hello Python
Example 4: Data Hiding
Closures provide a form of data hiding, encapsulating state that cannot be accessed directly from outside:
def create_bank_account(initial_balance):
balance = initial_balance
def deposit(amount):
nonlocal balance
balance += amount
return balance
def withdraw(amount):
nonlocal balance
if amount > balance:
raise ValueError("Insufficient funds")
balance -= amount
return balance
def get_balance():
return balance
return deposit, withdraw, get_balance
deposit, withdraw, get_balance = create_bank_account(100)
deposit(50)
print(get_balance()) # 150
The balance variable is private to the closure — it cannot be accessed or modified directly from outside.
Closures and Decorators
Decorators are one of the most important applications of closures in Python. A decorator is a function that takes another function as an argument and returns a new function that wraps the original:
def logger(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with {args}")
result = func(*args, **kwargs)
print(f"{func.__name__} returned {result}")
return result
return wrapper
@logger
def add(a, b):
return a + b
add(3, 5)
# Output:
# Calling add with (3, 5)
# add returned 8
The logger function is a closure factory: it captures the func argument and returns wrapper, which remembers func and adds logging behaviour around it.
Common Pitfalls and How to Avoid Them
1. Capturing Variables in Loops
A common pitfall occurs when creating closures inside a loop:
def create_functions():
funcs = []
for i in range(3):
def f():
return i
funcs.append(f)
return funcs
for f in create_functions():
print(f()) # 2 2 2 — not 0 1 2!
All closures capture the same variable i by reference. By the time the functions are called, the loop has finished and i is 2. To fix this, bind the value at the time of creation:
def create_functions():
funcs = []
for i in range(3):
def f(i=i): # Default argument captures the current value
return i
funcs.append(f)
return funcs
for f in create_functions():
print(f()) # 0 1 2
2. Forgetting nonlocal
Modifying a captured variable requires the nonlocal keyword:
def make_counter():
count = 0
def counter():
count += 1 # UnboundLocalError: local variable 'count' referenced before assignment
return count
return counter
Use nonlocal count inside the inner function to indicate that count refers to the variable in the enclosing scope.
3. Memory Leaks
Because closures hold references to captured variables, they can prevent garbage collection of large objects. If a closure captures a large data structure, that data remains in memory as long as the closure exists. Be mindful of what you capture and consider using weakref if necessary.
4. Assuming Closures Are Faster Than Classes
Closures are not inherently faster than classes. The performance difference is usually negligible, and readability and maintainability should guide your choice.
Closures in Functional Programming
In functional programming, closures are essential for several reasons:
- Data encapsulation without classes — closures provide a lightweight way to encapsulate state.
- Function composition — closures enable the creation of specialised functions from general‑purpose ones.
- Memoization — closures can cache results to avoid redundant computation.
- Lazy evaluation — closures can delay computation until the result is needed.
Memoization with Closures
def memoize(func):
cache = {}
def wrapper(x):
if x not in cache:
cache[x] = func(x)
return cache[x]
return wrapper
@memoize
def slow_square(x):
print(f"Computing square of {x}")
return x * x
print(slow_square(5)) # Computing square of 5 \n 25
print(slow_square(5)) # 25 (cached, no computation)
The closure captures the cache dictionary, which persists across calls.
Summary
Closures are a fundamental concept in functional programming that enable functions to capture and remember their environment. In Python, closures are created when a nested function references variables from its enclosing scope and is returned from that scope. The inner function retains access to those variables through the __closure__ attribute, even after the outer function has finished executing.
Closures are powerful tools for creating function factories, maintaining state without global variables, implementing data hiding, and building decorators. They are an essential part of Python's functional programming toolkit and are widely used in real‑world applications, from web frameworks to data processing pipelines.
By understanding how closures work and when to use them, you can write more expressive, maintainable, and functional Python code.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Function Composition
Next
Currying
-
What Is a Closure?
-
Three Conditions for a Closure
-
How Closures Work Internally
- Capturing Mutable Variables
-
Closures vs. Classes
- When to Use Closures
- When to Use Classes
-
Practical Examples of Closures
- Example 1: Function Factories
- Example 2: Maintaining State
- Example 3: String Formatting
- Example 4: Data Hiding
-
Closures and Decorators
-
Common Pitfalls and How to Avoid Them
- 1. Capturing Variables in Loops
- 2. Forgetting
nonlocal - 3. Memory Leaks
- 4. Assuming Closures Are Faster Than Classes
-
Closures in Functional Programming
- Memoization with Closures
-
Summary
