Basic Closure
A closure is a nested function that remembers variables from its enclosing scope even after the outer function has finished executing. It's created when the inner function is returned.
def multiplier(factor):
def multiply(x):
return x * factor
return multiply
times3 = multiplier(3)
print(times3(7))
Try it Yourself →
Counter Closure
Closures can maintain state across calls. The inner function captures and modifies a variable from the outer scope, which persists between invocations.
def make_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
c = make_counter()
print(c())
print(c())
print(c())
Try it Yourself →