Sub topic 12
Representation invariants
This chapter assumes you can read Python classes, know what a list and a set are, and understand exceptions and assertions. It also assumes you have seen how an abstract data type (ADT) separates an interface from an implementation. Here you will learn what a representation invariant is, how to write one down, how to check it in code, and which mistakes it catches.
The problem an invariant solves
An ADT promises behavior to its clients. An implementation stores data in some concrete form, called the representation. Not every value the representation can hold is a legal state for the ADT.
Take an IntSet that stores integers in a Python list. The list [3, 5, 3] is a valid Python list. But it does not describe a sensible set, because a set cannot hold 3 twice. If size() counts list entries, it would report 3 for this set. The right answer is 2.
A representation invariant (often shortened to "rep invariant") is a condition on the representation that must be true for every object that is fully constructed and at rest. "At rest" means no operation of the ADT is currently running. The invariant describes which concrete values are legal. Every operation can then assume it holds on entry, and every operation must make sure it holds again on exit.
Writing the invariant for IntSet
The IntSet from this tutorial's examples states its invariant in the class docstring.
class IntSet:
"""A set of integers.
Abstraction function: the list [a, b, c] represents the set {a, b, c}.
Representation invariant: _items contains no duplicates.
"""
def __init__(self):
self._items = []
self._check_rep()
def _check_rep(self):
assert len(self._items) == len(set(self._items))
def add(self, x):
if x not in self._items:
self._items.append(x)
self._check_rep()
def contains(self, x):
return x in self._items
def size(self):
return len(self._items)The invariant here is "no duplicates". Look at how it is used:
__init__establishes it. An empty list has no duplicates.addrelies on it and preserves it. The checkx not in self._itemsis what keeps duplicates out.containsandsizerely on it.sizecan returnlen(self._items)only because duplicates are impossible.
That last point is the main value of an invariant. It lets each operation stay simple. Without the invariant, size would need to count distinct items every time it was called.
The invariant is a contract between operations
Think of the invariant as a contract among all the methods in the class.
- The constructor must make the invariant true.
- Every public operation may assume it is true when called.
- Every public operation must leave it true when it returns.
If each operation keeps its part, the invariant holds for the whole life of the object. This is an argument by induction. It holds at creation, and each step preserves it, so it holds after any sequence of calls.
The argument breaks the moment one operation is wrong, or when code outside the class changes the representation directly. The second case is called representation exposure and is covered later in this chapter and in its own chapter.
An operation may break the invariant temporarily while it runs. For example, a method that moves an item between two internal lists is briefly inconsistent between the two steps. The requirement applies at the boundaries, on entry and on return.
Checking the invariant with checkRep
Writing the invariant in a comment helps readers. Writing it as code helps you find bugs. The usual practice is a private method, often named _check_rep, that asserts the invariant. You call it at the end of the constructor and at the end of every operation that changes the representation.
Observers that do not change state usually do not need the call. Some teams add it at the start of observers too, which catches corruption from outside the class sooner.
Here is a deliberately broken version of add, so you can see the check work.
class BrokenIntSet:
"""A set of integers.
Representation invariant: _items contains no duplicates.
"""
def __init__(self):
self._items = []
self._check_rep()
def _check_rep(self):
assert len(self._items) == len(set(self._items)), "duplicate in _items"
def add(self, x):
self._items.append(x) # bug: forgot to test for membership
self._check_rep()
def size(self):
return len(self._items)
s = BrokenIntSet()
s.add(3)
s.add(5)
try:
s.add(3)
except AssertionError as error:
print("caught:", error)
# caught: duplicate in _itemsThe failure is reported at the call to add(3), which is the operation that caused the damage. Without _check_rep, the bad state would sit unnoticed until size() returned a wrong number much later. By then the line that caused the bug could be far from the symptom.
Cost of checking
IntSet._check_rep builds a set from the list, which takes time proportional to the number of items. Calling it after every add turns an operation that already scans the list into one that does roughly double the work. For a short list this does not matter.
For large structures, a full check on every call can change the cost of the whole program. Common choices are:
- Keep checks on during development and tests.
- Turn them off in production. Python skips
assertstatements when run withpython -O. - Check a cheaper necessary condition on every call and run the full check only in tests.
A check that raises with assert is for catching programmer bugs. Do not use it to validate input from clients. Bad input should raise a documented exception such as ValueError, because it must still work when assertions are turned off.
Invariants for the stack implementations
Representation invariants are not only for sets. The two stack implementations from earlier chapters have invariants too, though they are simple.
| Implementation | Representation | Invariant |
|---|---|---|
| `ListStack` | Python list `_items` | `_items` is a list. The last element is the top. |
| `LinkedStack` | Chain of `_Node` objects from `_head` | Following `next` from `_head` reaches `None` and never revisits a node. |
The linked version is more interesting. If a bug made a node's next point back to an earlier node, the chain would form a cycle. Code that walks the chain would then loop forever. A check can detect this directly.
class _Node:
def __init__(self, value, next_node):
self.value = value
self.next = next_node
def chain_is_acyclic(head):
seen = set()
node = head
while node is not None:
if id(node) in seen:
return False
seen.add(id(node))
node = node.next
return True
a = _Node(1, None)
b = _Node(2, a)
print(chain_is_acyclic(b)) # True
a.next = b # corrupt the chain on purpose
print(chain_is_acyclic(b)) # FalseThe function stores id(node), the identity of each node, in a set. If it sees the same identity twice, the chain has a cycle. A LinkedStack._check_rep could call this helper.
Choosing a good invariant
A useful invariant is neither too weak nor too strong.
- Too weak. It allows states that the operations cannot handle. For
IntSet, the invariant "_itemsis a list" would not stop duplicates, sosizewould be wrong. - Too strong. It forbids states that are harmless, and it forces extra work in every operation. If you required
_itemsto be sorted,addwould have to insert in order, even though a set has no order.
Different invariants lead to different implementations of the same ADT. A sorted list of integers allows binary search in contains. The price is a more expensive add. The invariant is part of the design, and it ties directly to the cost trade-offs from the previous chapter.
A practical approach is to ask what each operation needs to be true about the data, and write down exactly that.
Invariants and representation exposure
The invariant is only as safe as the code that can touch the representation. Suppose IntSet had a method items() that returned self._items directly. A client could then write s.items().append(3) twice and put duplicates into the list. No method of IntSet would have run, so no _check_rep would have caught it.
This is why the invariant and encapsulation go together. The invariant can be trusted only when every change to the representation passes through the class's own methods. Returning a copy, or an immutable view, protects it. The details come in the chapter on representation exposure.
Common mistakes
- Never writing the invariant down. If it lives only in your head, the next person who edits the class will break it.
- Checking only in the constructor. The constructor is easy to get right. Bugs appear in the mutators.
- Forgetting an early return. If
addreturns before reaching_check_rep, the check is skipped on that path. Placing the check in atry/finallyblock or restructuring the method avoids this. - Using the invariant to describe the ADT. "The set has no duplicates" is true of the abstract set by definition. The invariant is about the list, which could hold duplicates if the code were wrong.
- Treating
assertas input validation. Assertions can be disabled, and they signal bugs, not user mistakes.
Exercise
A SortedIntSet stores its integers in a Python list _items. Write its representation invariant. Then explain why contains can use binary search (the bisect module) as a result of that invariant.
Show answer
Invariant: _items has no duplicates and is sorted in strictly increasing order, so _items[i] < _items[i + 1] for every valid i. In code, assert all(a < b for a, b in zip(self._items, self._items[1:])). Strictly increasing covers both "sorted" and "no duplicates" in one condition. Because the invariant guarantees the list is sorted, contains can use bisect.bisect_left to find the position of x in O(log n) time and compare the item at that position. Binary search gives wrong answers on unsorted lists, so the algorithm is correct only because every operation, especially add, preserves the invariant.
Exercise
This add method has a bug that _check_rep will not catch on one path. Which path, and how do you fix it?
def add(self, x):
if x in self.items:
return
self.items.append(x)
self.checkrep()
Show answer
The early return on the duplicate path skips _check_rep. Here the skipped path leaves the state unchanged, so it cannot break the invariant, and the code is fine. The risk is in the habit: if a later edit changes that path so it modifies _items, nothing would check it. A safer structure is to run the check in a finally block, or to place a single _check_rep() call at the one exit of the method, for example by using if x not in self._items: self._items.append(x) followed by self._check_rep().