Consider a small exhibition label that holds a starting and ending year. The start must not be later than the end. That condition is an invariant: a statement we want to remain true whenever the object is successfully created or updated through its supported operations.
class YearSpan:
def __init__(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)
print(span.bounds())
try:
YearSpan(1930, 1920)
except ValueError as error:
print(error)
Output:
(1910, 1920)
start must not follow end
The first call passes the condition and stores two attributes. The second raises ValueError during initialization; the caller receives no successfully initialized YearSpan. The tuple returned by bounds communicates both values in order. This small example assumes integer years; it does not enforce their types or model calendar details.
Checking only the starting state is insufficient if later operations can change either year. An update needs to check the proposed pair before storing either part. Otherwise a formerly valid span can become invalid. A leading underscore signals an internal attribute, not a lock; we will examine that boundary shortly.