A closure is an inner function that remembers the variables of the outer function that created it, even after the outer function has finished.
The program
python
def multiplier(n): def multiply(x): return x * n return multiply double = multiplier(2) triple = multiplier(3) print(double(5)) print(triple(5)) print(double(10))
output
10 15 20
How it works
multiplier(2)definesmultiplyand returns it without calling it. Note that thereturnline has no brackets aftermultiply.multiplyusesn, which belongs tomultiplier. Python keeps thatnwith the inner function. Sodoubleremembersn = 2, andtripleremembersn = 3.- Each call to
multipliercreates a new, separate closure.
A counter with nonlocal
An inner function can read the outer variable without any extra code. To change it, declare it nonlocal first. Without that line, count += 1 raises an UnboundLocalError:
python
def make_counter(): count = 0 def increment(): nonlocal count count += 1 return count return increment counter = make_counter() print(counter()) print(counter()) print(counter()) other = make_counter() print(other())
output
1 2 3 1
counter and other each have their own count. Closures are the idea behind decorators, which wrap a function inside another function in the same way.