Python - Closures
In Python, functions can be defined inside other functions. Sometimes, the inner function can remember and use variables from the outer function even after the outer function has finished execution.
This powerful concept is called a Closure.
In this tutorial, you will learn what closures are, how they work, and how to use them with clear examples.
What is a Closure?
A closure is:
A nested function that remembers variables from its enclosing (outer) function, even after the outer function has finished execution.
Key Components of a Closure
A closure must have:
- A nested function
- A variable from the outer function
- The inner function returned from the outer function
Simple Example of Closure
def outer_function(msg):
def inner_function():
print(msg)
return inner_function
my_func = outer_function("Hello, Python Closures!")
my_func()Output
Hello, Python Closures!How Closures Work
Step-by-step:
outer_function()is called- It defines
inner_function() inner_function()uses variablemsg- Outer function returns inner function
- Even after outer finishes,
msgis remembered
Closure with Parameters
def multiplier(x):
def multiply(y):
return x * y
return multiply
double = multiplier(2)
triple = multiplier(3)
print(double(5))
print(triple(5))Output
10
15Why Closures Work
Closures store:
The function + its surrounding environment (variables)
This is called lexical scoping.
Real-World Example: Counter Using Closure
def counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
c = counter()
print(c())
print(c())
print(c())Output
1
2
3What is nonlocal?
The nonlocal keyword allows inner functions to modify variables from the outer function.
Closure vs Normal Function
| Feature | Normal Function | Closure |
|---|---|---|
| Remembers outer variables | No | Yes |
| State retention | No | Yes |
| Scope usage | Local only | Enclosing scope |
Real-World Use Cases
Closures are used in:
- Decorators
- Function factories
- Callback functions
- Event handling
- Encapsulation of state
Example: Function Factory
def power(exponent):
def calculate(base):
return base ** exponent
return calculate
square = power(2)
cube = power(3)
print(square(4))
print(cube(4))Output
16
64Closures in Decorators (Advanced Concept)
Closures are the foundation of decorators.
def decorator(func):
def wrapper():
print("Before function")
func()
print("After function")
return wrapperAdvantages of Closures
- Maintain state without classes
- Encapsulate logic
- Cleaner functional programming
- Useful in decorators
- Memory efficient
Disadvantages
- Can be confusing for beginners
- Harder to debug
- Overuse may reduce readability
Common Mistakes
1. Forgetting nonlocal keyword
# variable won't update without nonlocal2. Confusing closure with normal nested function
3. Overusing closures instead of classes
Best Practices
1. Use closures for small state management
2. Prefer classes for complex systems
3. Use meaningful variable names
4. Understand scope rules clearly
Summary
Closures in Python are functions that remember variables from their enclosing scope even after the outer function has finished execution. They are powerful tools for creating function factories, decorators, and maintaining state without using classes.
Key Takeaways
- A closure is a nested function
- It remembers outer variables
- Uses lexical scoping
- Requires return of inner function
- Useful for decorators and state handling
Mastering closures helps you understand advanced Python concepts like decorators and functional programming.


0 Comments