Code

Closures & nonlocal

A function defined inside another function can use the outer function's variables, even after the outer function has returned. That inner function plus the variables it remembers is a closure.

def make_greeter(greeting):
    def greet(name):
        return f"{greeting}, {name}!"
    return greet

hello = make_greeter("Hello")
hello("Ada")   # 'Hello, Ada!'  -- greeting is remembered

Reading an outer variable just works. Rebinding it (x = ..., x += 1) would normally create a new local variable instead, so you must declare it nonlocal:

def make_meter():
    total = 0
    def add(n):
        nonlocal total   # use the outer 'total'
        total += n
        return total
    return add

Each call to make_meter() creates a fresh total, so two meters never interfere. Closures are a lightweight way to bundle a little private state with behavior, and they are exactly how decorators work.

Assignment

  1. Finish make_counter(): each call to the returned tick() returns the next number, starting at 1.
  2. Write make_tank(litres) that returns a function draw(amount):
    • if amount is more than what's left, raise ValueError("not enough fuel") and leave the tank unchanged;
    • otherwise subtract it and return the litres remaining.