Sub topic 5
Ordering objects and functools.total_ordering
This chapter shows how Python decides what a < b means for your own classes, and how functools.total_ordering reduces the amount of code you write. It assumes you have read the chapters on __eq__ and __hash__ and on returning NotImplemented. It also assumes you are comfortable with tuples and with sorted().
The six comparison methods
Python has six comparison operators. Each one maps to a method on the left operand's type.
| Expression | Method called first | Reflected method tried on the right operand |
|---|---|---|
| `a < b` | `a.__lt__(b)` | `b.__gt__(a)` |
| `a <= b` | `a.__le__(b)` | `b.__ge__(a)` |
| `a > b` | `a.__gt__(b)` | `b.__lt__(a)` |
| `a >= b` | `a.__ge__(b)` | `b.__le__(a)` |
| `a == b` | `a.__eq__(b)` | `b.__eq__(a)` |
| `a != b` | `a.__ne__(b)` | `b.__ne__(a)` |
The reflected column differs from arithmetic. There is no __rlt__. The reflection of < is > with the operands swapped, because a < b and b > a ask the same question.
__ne__ needs no work from you. By default it calls __eq__ and inverts the result, unless __eq__ returned NotImplemented.
How Python resolves a comparison
For a < b, Python follows these steps:
- If
type(b)is a proper subclass oftype(a)and overrides the reflected method, Python triesb.__gt__(a)first. - Otherwise it calls
a.__lt__(b). - If that returns
NotImplemented, it tries the reflected methodb.__gt__(a). - If that also returns
NotImplemented, Python raisesTypeError.
For == and != the last step is different. Python falls back to comparing identity (a is b) instead of raising an error. This is why Vector(1, 2) == "text" returns False and does not fail.
What happens with only `__lt__`
Sorting needs very little. list.sort() and sorted() use only <. The min() and max() functions work with __lt__ alone, because > reflects to < on the other operand.
class Box:
def __init__(self, size):
self.size = size
def __repr__(self):
return f'Box({self.size})'
def __lt__(self, other):
if not isinstance(other, Box):
return NotImplemented
return self.size < other.size
boxes = [Box(3), Box(1), Box(2)]
print(sorted(boxes)) # [Box(1), Box(2), Box(3)]
print(max(boxes)) # Box(3)
print(Box(2) > Box(1)) # True, reflected to Box(1).__lt__(Box(2))
try:
Box(1) <= Box(2)
except TypeError as e:
print(e) # '<=' not supported between instances of 'Box' and 'Box'Box(2) > Box(1) works because Box has no __gt__, so Python calls Box(1).__lt__(Box(2)). <= has no such partner. Its reflection is __ge__, which is also missing, so you get a TypeError.
Defining one method works for sorting, but users will expect all four operators. Writing four near-identical methods is tedious and invites bugs.
Using functools.total_ordering
functools.total_ordering is a class decorator. You supply __eq__ and any one of __lt__, __le__, __gt__ or __ge__. The decorator generates the other three.
from functools import total_ordering
@total_ordering
class Version:
def __init__(self, major, minor):
self.major = major
self.minor = minor
def __repr__(self):
return f'Version({self.major}, {self.minor})'
def __eq__(self, other):
if not isinstance(other, Version):
return NotImplemented
return (self.major, self.minor) == (other.major, other.minor)
def __lt__(self, other):
if not isinstance(other, Version):
return NotImplemented
return (self.major, self.minor) < (other.major, other.minor)
def __hash__(self):
return hash((self.major, self.minor))
print(Version(1, 2) <= Version(1, 3)) # True
print(Version(2, 0) >= Version(2, 0)) # True
print(sorted([Version(2, 0), Version(1, 5)])) # [Version(1, 5), Version(2, 0)]
print(max(Version(1, 0), Version(0, 9))) # Version(1, 0)The comparison of tuples inside __lt__ is a common idiom. Tuples compare element by element from the left, so (1, 5) < (2, 0) is decided by the first element. Use this whenever your ordering is "by field A, then by field B".
The generated methods are built from __lt__ and __eq__:
a <= bisa < b or a == b.a > bisnot (a < b) and a != b.a >= bisnot (a < b).
The generated versions also pass NotImplemented through, so mixed-type comparisons still reach the reflected method or raise TypeError.
Requirements and limits
The decorator raises ValueError if you define none of the four ordering methods:
from functools import total_ordering
try:
@total_ordering
class Broken:
pass
except ValueError as e:
print(e) # must define at least one ordering operation: < > <= >=Keep these points in mind:
- You must provide
__eq__. The decorator does not add it. Without your own__eq__, equality falls back to identity, and the derived<=and>=will give wrong answers for objects that you think of as equal. - Define
__hash__when you define__eq__. A class that defines__eq__without__hash__gets__hash__ = Noneand its instances cannot go in sets or serve as dict keys. TheVersionclass above defines both. - The derived methods are slower. Each one makes extra comparison calls through Python code. For a hot sorting path, write the methods by hand or sort with a
keyfunction. - The decorator assumes a total order. Exactly one of
a < b,a == bandb < amust be true. Floats with NaN break this, and so do partial orders such as set inclusion. For those, write all methods yourself.
Keeping ordering consistent with equality
Three rules keep your class predictable:
- Equal objects must not be ordered. If
a == b, thena < banda > bmust both be false. - Compare the same fields in
__eq__and__lt__. If__eq__looks at(major, minor)but__lt__looks only atmajor, thenVersion(1, 2) == Version(1, 3)is false while neither is less than the other. Sorting and<=will then disagree. - Equal objects must hash equal. This is the rule from the previous chapter. Ordering adds no new hashing requirement, but a class that is orderable is often used in sets and dicts, so check it.
Mixed types
Returning NotImplemented for unknown types makes comparison fail clearly:
from functools import total_ordering
@total_ordering
class Version:
def __init__(self, major, minor):
self.major = major
self.minor = minor
def __eq__(self, other):
if not isinstance(other, Version):
return NotImplemented
return (self.major, self.minor) == (other.major, other.minor)
def __lt__(self, other):
if not isinstance(other, Version):
return NotImplemented
return (self.major, self.minor) < (other.major, other.minor)
__hash__ = None # unhashable in this variant, for brevity
print(Version(1, 2) == (1, 2)) # False, == falls back to identity
try:
Version(1, 2) < (1, 3)
except TypeError as e:
print(e) # '<' not supported between instances of 'Version' and 'tuple'Do not return False for unknown types in __lt__. That hides bugs: Version(1, 2) < "banana" would quietly produce False and sorted lists of mixed items would come out in arbitrary order.
Alternatives to hand-written ordering
You do not always need dunder methods.
- A
keyfunction.sorted(items, key=lambda v: (v.major, v.minor))sorts without changing the class. Use this when the ordering is local to one call site. @dataclass(order=True). This generates all four methods by comparing the fields as a tuple, in declaration order. It raisesTypeErrorunless both operands are of exactly the same class. It is the shortest choice when the natural order is "all fields in order".total_ordering. Choose it when the ordering logic is custom, for example comparing by a computed value, but you want all four operators.
Exercise
A class defines __eq__ and __lt__ and is decorated with @total_ordering. You then evaluate a >= b where a < b is True. What does the derived __ge__ return, and which two operations does it use?
Show answer
It returns False. The derived __ge__ is not (a < b), so it calls __lt__ and negates the result, passing NotImplemented through unchanged when __lt__ returns it.
Exercise
Write a class Money with amount (an int of cents) and currency (a string). Instances with the same currency should be ordered by amount. Comparing different currencies should raise TypeError, but == between different currencies should simply be False. Use total_ordering.
Show answer
from functools import totalordering @totalordering class Money: def _init(self, amount, currency): self.amount = amount self.currency = currency def eq(self, other): if not isinstance(other, Money): return NotImplemented return (self.amount, self.currency) == (other.amount, other.currency) def lt(self, other): if not isinstance(other, Money): return NotImplemented if self.currency != other.currency: raise TypeError('cannot order different currencies') return self.amount < other.amount def hash_(self): return hash((self.amount, self.currency))