Make supported changes visible

Lesson 7 of 19 · Python Object Design

Let’s give a year span an operation that changes both ends together. A method is a function defined on a class. An ordinary instance method receives the object as its first parameter, conventionally called self.

class YearSpan:
    def __init__(self, start, end):
        if start > end:
            raise ValueError("start must not follow end")
        self._start = start
        self._end = end

    def revise(self, start, end):
        if start > end:
            raise ValueError("start must not follow end")
        self._start = start
        self._end = end

    def bounds(self):
        return (self._start, self._end)

span = YearSpan(1910, 1920)
result = span.revise(1915, 1925)
print(span.bounds())
print(result)
try:
    span.revise(1940, 1930)
except ValueError as error:
    print(error)
print(span.bounds())

Output:

(1915, 1925)
None
start must not follow end
(1915, 1925)

span.revise(1915, 1925) supplies span as self, then the two explicit arguments. For this ordinary method, YearSpan.revise(span, 1915, 1925) has the same effect. revise updates the instance and, because it has no explicit return, returns None. In contrast, bounds returns a value without updating the span.

The failed call checks both proposed values before either assignment. Raising the exception stops that call; the old pair is still present. This is a guarantee about this sequential example, not a general transaction or concurrency guarantee.

request pair --> check ordering --> assign both
                       |
                       +--> invalid: raise; keep old pair

A standalone function could also check a pair; a method makes the operation discoverable alongside the state it changes. The repeated check in initialization and revision represents the same rule: as the implementation grows, a shared validation function could give it one home. It must be called on every supported path that changes the pair.

Chapter contents