Category: python
What Is a Closure?
Published on 27 Oct 2026
Explanation
A closure is an inner function that retains access to variables from its enclosing scope after the outer function returns.
Code:
def outer():
message = 'Hello from outer'
def inner(): print(message)
return inner
fn = outer()
fn()
Explanation
An outer function can accept configuration and return a function that uses it.
Code:
def make_multiplier(factor):
def multiply(number): return number * factor
return multiply
double = make_multiplier(2)
print(double(10))
Explanation
Use nonlocal to reassign a variable from an enclosing function.
Code:
def counter_factory():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
c = counter_factory()
print(c(), c())
Explanation
Closures look up captured variables when called. Lambdas created in a loop can all observe the final loop value.
Code:
functions = [] for n in range(3): functions.append(lambda: n) print([f() for f in functions])
Explanation
Capture the current loop value in a default argument to give each lambda its own value.
Code:
functions = [] for n in range(3): functions.append(lambda n=n: n) print([f() for f in functions])