Functions that remember: closures and nonlocal
🌍 In real life. A tea stall gives each regular customer a stamp card: ten stamps, and the next cup is free. Every card remembers its own stamps, and the stall can hand out as many cards as it likes. Nobody keeps one big shared list of everyone's stamps.
Python can make functions like those cards. The idea in one sentence: a function defined inside another function can use the outer function's names, and it keeps them even after the outer function has finished; that function together with the names it keeps is a closure.
Its words:
- nested function: a
definside anotherdef - enclosing function: the outer one; its names are the inner function's enclosing scope
- closure: an inner function plus the outer names it uses, kept alive after the outer function returns
nonlocal name: says that assigning tonameinside the inner function changes the enclosing function'sname- LEGB: the order Python looks a name up in: Local, Enclosing, Global, Built-in
Step by step, for c = make_counter(10) and then c(1):
- calling
make_counter(10)opens a frame withstart = 10andcount = 10 - it builds
stepand gives it back, without calling it - the frame closes, but
countsurvives, becausestepstill uses it: it travels withstep, like a backpack c(1)runsstep;nonlocal countmakescount += 1change the backpack'scount
Watch two counters, each with its own backpack:
Why nonlocal is needed. Python decides whether a name is local by looking at the whole function before it runs: if the function assigns to a name anywhere (count += 1 is an assignment), that name is local to it, everywhere in it. So without nonlocal, count += 1 tries to read a brand-new local count that has no value yet, and stops with an UnboundLocalError. Reading an outer name needs nothing special, and neither does changing what's inside an outer list (items.append(x) doesn't assign to items). nonlocal is like global (Lesson 15.2), but for the enclosing function's names instead of the program's:
def make_counter(start):
count = start
def step(by=1):
nonlocal count # count is make_counter's, not a new local
count += by
return count
return step
tea = make_counter(0)
coffee = make_counter(5)
print(tea(), tea(), coffee(), tea())
def make_multiplier(k):
def times(x):
return x * k # only reads k: no nonlocal needed
return times
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(7), triple(7))When to use one. A closure is a small object with one job: it keeps a little state (a count, a setting like k) without a class or a global. Chapter 27's decorators are built from closures, and so is the tree diameter in Lesson 47.4, where the inner function updates best with nonlocal best. When the state grows to several values and several actions, a class (Chapter 21) is clearer.
Mistakes and edge cases.
- forgetting
nonlocal:count += 1without it is an UnboundLocalError, as the animation showed nonlocalfor a name no enclosing function has: a SyntaxError ("no binding for nonlocal 'x' found"); for a program-level name useglobal, or better, pass it in- closures in a loop see the last value:
[lambda: i for i in range(3)]makes three functions that all read the samei, which ends at 2, so all of them give 2; fix it with a default,lambda i=i: i, which copies the value at that moment - calling instead of returning:
return step()gives back a number, not the function; return the function itself, without brackets
Quiz
What does this print?
def make_counter(start): count = start def step(by=1): nonlocal count # count is make_counter's, not a new local count += by return count return step a = make_counter(0) b = make_counter(10) print(a(), a(), b(), a())What does this print?
def make_greeter(greeting): def greet(name): return greeting + ", " + name return greet hi = make_greeter("Hi") print(hi("Ana"))What does this print?
fs = [lambda: i for i in range(3)] print([f() for f in fs])Inside a nested function, which line needs
nonlocal totalfirst?- total = total + x
- print(total)
- total.append(x), when total is a list
Calling the counter stops with an UnboundLocalError. Which line is missing something before it?
def make_counter(): count = 0 def step(): count += 1 return count return step
Coding tasks
Write
make_multiplier(k): it returns a function that takes a numberxand returnsx * k.Fix
make_counter(start): each call of the function it returns should add 1 to its own count and return it, and two counters must not share a count.Write
make_averager(): it returns a functionadd(x)that remembers every number it has been given and returns their average so far.