How to Create Closure in Python: Simple Guide with Examples
In Python, a
closure is created when a nested function captures variables from its enclosing scope. You create a closure by defining a function inside another function and returning the inner function, which remembers the outer function's variables.Syntax
A closure in Python involves three parts:
- An
outer functionthat defines a variable. - An
inner functiondefined inside the outer function that uses the outer variable. - The outer function returns the inner function, which keeps access to the outer variable even after the outer function finishes.
python
def outer_function(msg): def inner_function(): print(msg) return inner_function
Example
This example shows how a closure remembers the message from the outer function and prints it when called later.
python
def outer_function(msg): def inner_function(): print(msg) return inner_function closure_func = outer_function('Hello, closure!') closure_func()
Output
Hello, closure!
Common Pitfalls
One common mistake is expecting the closure to capture the current value of a variable in a loop, but it actually captures the variable itself, which may change later.
To fix this, use default arguments to bind the current value.
python
def create_funcs(): funcs = [] for i in range(3): def inner(): print(i) # This will print 2 for all calls funcs.append(inner) return funcs funcs = create_funcs() for f in funcs: f() # Correct way: def create_funcs_fixed(): funcs = [] for i in range(3): def inner(x=i): # bind current i print(x) funcs.append(inner) return funcs funcs_fixed = create_funcs_fixed() for f in funcs_fixed: f()
Output
2
2
2
0
1
2
Quick Reference
- Define an inner function inside an outer function.
- Use variables from the outer function inside the inner function.
- Return the inner function from the outer function.
- The returned function is a closure that remembers the outer variables.
Key Takeaways
A closure is a function that remembers variables from its enclosing scope.
Create closures by defining and returning an inner function that uses outer variables.
Closures keep the outer variables alive even after the outer function finishes.
Beware of variable binding in loops; use default arguments to capture current values.
Closures help create functions with customized behavior based on saved data.