Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

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 += 1 raises UnboundLocalError, because Python thinks count is a new local variable.
  • You only need nonlocal to 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: nonlocal is like global (Part 5) but for the enclosing function, the E in LEGB. The remembered values live in festive.__closure__.

Done here? The practice set for Part 10 โ€” 8 exercises with solutions โ€” is on the part page.

Search the guide