Functions
Closures
Define a function inside another function when the inner behavior needs to remember setup from the outer call. The returned function keeps access to factor.
Source
def make_multiplier(factor):
def multiply(value):
return value * factor
return multiply
double = make_multiplier(2)
print(double(5))Output
10Calling the outer function again creates a separate closure. triple uses the same inner code, but remembers a different factor.
Source
triple = make_multiplier(3)
print(triple(5))Output
15Closures bind names, not values. Lambdas defined in a loop all reference the same loop variable, so calling them later sees its final value. Capture the value at definition time by binding it as a default argument — lambda i=i: i — so each closure remembers its own i.
Source
late = []
for i in range(3):
late.append(lambda: i)
print([f() for f in late])
bound = []
for i in range(3):
bound.append(lambda i=i: i)
print([f() for f in bound])Output
[2, 2, 2]
[0, 1, 2]Notes
- A closure keeps access to names from the scope where the inner function was created.
- Each call to the outer function can create a separate remembered environment.
- Closures are useful for callbacks, small factories, and decorators.
- Closures bind names, not values; capture loop variables with
lambda x=x: ...to freeze them at definition time.
See also
- related: Functions
- related: Lambdas
- related: Decorators
- related: Partial Functions
Run the complete example
Expected output
10
15
[2, 2, 2]
[0, 1, 2]
Execution time appears here after you run the example.