Python 3D Academyবাংলা

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 def inside another def
  • 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 to name inside the inner function changes the enclosing function's name
  • 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):

  1. calling make_counter(10) opens a frame with start = 10 and count = 10
  2. it builds step and gives it back, without calling it
  3. the frame closes, but count survives, because step still uses it: it travels with step, like a backpack
  4. c(1) runs step; nonlocal count makes count += 1 change the backpack's count

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 += 1 without it is an UnboundLocalError, as the animation showed
  • nonlocal for a name no enclosing function has: a SyntaxError ("no binding for nonlocal 'x' found"); for a program-level name use global, 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 same i, 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

  1. 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())
  2. What does this print?

    def make_greeter(greeting):
        def greet(name):
            return greeting + ", " + name
        return greet
    
    hi = make_greeter("Hi")
    print(hi("Ana"))
  3. What does this print?

    fs = [lambda: i for i in range(3)]
    print([f() for f in fs])
  4. Inside a nested function, which line needs nonlocal total first?

    • total = total + x
    • print(total)
    • total.append(x), when total is a list
  5. 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

  1. Write make_multiplier(k): it returns a function that takes a number x and returns x * k.

  2. 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.

  3. Write make_averager(): it returns a function add(x) that remembers every number it has been given and returns their average so far.