Part 10 / Topic 5 of 11
Closures
An inner function is a function defined inside another function. A closure is an inner function that remembers variables from the outer function, even after the outer function has finished. Think of a token machine at a clinic: each machine remembers its own last number.
Real-world example: ticket counters for two counters at a bank.
def make_counter(start=0):
count = start
def next_ticket():
nonlocal count # use the outer `count`, do not make a new local one
count += 1
return count
return next_ticket # return the function itself (no brackets)
counter_a = make_counter(100)
counter_b = make_counter()
print(counter_a(), counter_a()) # 101 102
print(counter_b()) # 1
print(counter_a()) # 103 (each closure keeps its own count)
- Without
nonlocal,count += 1raisesUnboundLocalError, because Python thinkscountis a new local variable. - You only need
nonlocalto change the outer variable. Just reading it works without it.
Closures can also "pre-fill" settings:
def make_discount(percent):
def apply(price):
return price * (100 - percent) / 100
return apply
festive = make_discount(20)
print(festive(1000)) # 800.0
๐ Going deeper:
nonlocalis likeglobal(Part 5) but for the enclosing function, the E in LEGB. The remembered values live infestive.__closure__.
Done here? The practice set for Part 10 โ 8 exercises with solutions โ is on the part page.