Functions

Closures

Inner functions can remember values from an enclosing scope.

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

10
MAKE_MULTIPLIERCELLfactor=2MULTIPLYuses cell
The inner function keeps a reference into the outer scope's cell, so the captured factor survives the outer return.

Calling 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

15

Closures 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

See also

Run the complete example

Example code

Expected output

10
15
[2, 2, 2]
[0, 1, 2]

Execution time appears here after you run the example.