Implement Rich Comparisons
Core idea
Rich comparison methods correspond to operators: __lt__ to <, __le__ to <=, __eq__ to ==, __ne__ to !=, __gt__ to > and __ge__ to >=. Return NotImplemented for operand types you cannot compare. Python can try the reflected comparison (for example, a < b can try b.__gt__(a)). If neither supports ordering, Python raises TypeError; equality instead falls back to identity. A strict subclass on the right can receive priority.
class Priority: def __init__(self, rank): self.rank = rank def __lt__(self, other): if not isinstance(other, Priority): return NotImplemented return self.rank < other.rankprint(Priority(2) < Priority(5))The operator compares the stored ranks.
Reflected ordering
class Left: def __lt__(self, other): return NotImplementedclass Right: def __gt__(self, other): return isinstance(other, Left)print(Left() < Right())After the left method declines, the reflected greater-than method runs.
Intentional failure: unsupported order
class Priority: def __lt__(self, other): return NotImplementedprint(Priority() < 3)Neither operand provides a supported ordering result.
Common mistake
NotImplemented is a sentinel value, not the NotImplementedError exception. Implementing lt alone does not automatically implement <=.
Practice
Implement lt and eq for a rank object. Test equal ranks and unrelated operands; explain what happens for <=.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Rich comparisons
Check your understanding of rich comparisons.
What is printed?
class A: def __lt__(self, other): return NotImplementedclass B: def __gt__(self, other): return Trueprint(A() < B())What is printed?
class A: def __eq__(self, other): return NotImplementeda = A()b = A()print(a == b)What happens?
class A: def __lt__(self, other): return Trueprint(A() <= A())How should an ordering method decline an unsupported operand?