Notice what must be remembered

Lesson 2 of 19 · Python Object Design

Now imagine a workshop spool. We need to remember how much ribbon is on it after each cut. Its state is the information we need at a particular moment; here it includes a label and remaining length. A rule says a cut cannot be longer than what remains.

A dictionary and a function can express this without a custom class:

def cut(spool, length):
    if length <= 0 or length > spool["remaining"]:
        raise ValueError("invalid cut")
    spool["remaining"] -= length

blue = {"label": "blue", "remaining": 12}
cut(blue, 4)
print(blue["label"], blue["remaining"])

Output:

blue 8

The dictionary is passed to cut; the function changes that dictionary rather than returning a new one. 12 - 4 leaves 8 for the next call. Here and in the following examples, lengths are assumed to be whole units unless stated otherwise.

before: blue -> {label: blue, remaining: 12}
cut(blue, 4)
after:  blue -> {label: blue, remaining: 8}

Another design can pass the current remaining length to a function and return a new remaining length, leaving the caller to store the result. That makes the state transition explicit instead of mutating this dictionary. The choice depends on who should own the state; neither approach automatically guarantees valid inputs.

The function is useful, but callers can also assign blue["remaining"] = -5 without using it. A class can put a record and its intended operations together, making the supported route easier to find. It does not by itself prevent callers from making unwanted changes. If the dictionary is simple and its callers can coordinate the rule clearly, keeping it may be a reasonable decision.

Chapter contents