Retained state and ownership

Lesson 13 of 20 · Functional Python: values, behavior, and choices

A closure can also retain a binding that changes. That makes previous calls relevant to later ones.

def make_counter():
    total = 0
    def record(amount):
        nonlocal total
        total = total + amount
        return total
    return record

north = make_counter()
south = make_counter()
print(north(2), north(2), south(2))
2 4 2

nonlocal makes assignment rebind total in the enclosing function. Without it, assignment would make total local to record, and reading that local before assignment would fail. Each factory call owns a separate binding. This counter is not pure: identical calls can return different results depending on its history.

Mutating an enclosed dictionary is different from rebinding its name. This thermostat setting retains one fixed key and replaces its value; the assignment changes the dictionary, so it needs no nonlocal:

def make_setting(initial):
    state = initial.copy()
    def set_temperature(degrees):
        state["temperature"] = degrees
        return state.copy()
    return set_temperature

original = {"temperature": 18, "unit": "C"}
set_temperature = make_setting(original)
view = set_temperature(20)
view["unit"] = "F"
print(set_temperature(21))
print(original)
{'temperature': 21, 'unit': 'C'}
{'temperature': 18, 'unit': 'C'}

The input copy separates the outer dictionaries, and the returned copy prevents changing view from changing retained state. Both copies are shallow: nested mutable values would still be shared. For nested structures copy the parts requiring independence, or consider copy.deepcopy for suitable objects; it can be costly and is not appropriate for every object. Captured bindings are not frozen snapshots. Explicit state passed to a pure function, or a class for richer state, can be easier to inspect.

Chapter index