Sub topic 5
Ordering objects and functools.total_ordering
This chapter assumes you can define classes with methods, and that you know __eq__ and __hash__ from the previous chapter. You should also be comfortable with tuples and with sorted().
How comparison operators map to methods
Each comparison operator calls a special method on the left operand.
| Operator | Method |
|---|---|
| `<` | `__lt__` |
| `<=` | `__le__` |
| `>` | `__gt__` |
| `>=` | `__ge__` |
| `==` | `__eq__` |
| `!=` | `__ne__` |
sorted(), list.sort(), min() and max() only need <. If the left operand's method returns NotImplemented, Python tries the reflected method on the right operand. For a < b, that means b.__gt__(a). If both sides decline, Python raises TypeError.
Writing the methods by hand
Comparing tuples is the simplest way to order an object by several fields. Tuples compare element by element, so (1, 2) < (1, 3) is True.
Writing all four ordering methods is repetitive. functools.total_ordering removes that work. You define __eq__ and one of __lt__, __le__, __gt__ or __ge__, and the decorator fills in the rest.
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(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 isinstance check followed by return NotImplemented matters. Without it, Version(1, 2) < 5 would fail with an AttributeError instead of a clear TypeError.
Common errors
- Missing
__eq__.total_orderingderives the other methods from__eq__and your one ordering method. The default identity-based__eq__makes the derived<=and>=wrong. - Inconsistent
__eq__and__lt__. If two objects are equal, neither should be less than the other. Compare the same fields in both methods. - Forgetting
__hash__. Defining__eq__sets__hash__toNone. Keep the hash consistent with equality if instances belong in sets or dict keys. - Returning
Falsefor unsupported types. ReturnNotImplementedso Python can try the other operand. - Speed. The methods that
total_orderinggenerates are a little slower than hand-written ones. This rarely matters, but it can in hot sorting loops.
Exercise
A class defines __eq__ and __lt__ and is decorated with @total_ordering. What happens when you evaluate Version(1, 0) < "1.0", given that both methods return NotImplemented for non-Version values?
Show answer
Python calls Version.__lt__, which returns NotImplemented. It then tries the reflected str.__gt__, which also returns NotImplemented. Python raises TypeError: '<' not supported between instances of 'Version' and 'str'.
Exercise
Why does sorted() work on a class that defines only __lt__, and what extra methods does total_ordering add?
Show answer
Sorting only uses < to compare items. total_ordering adds the missing methods among __le__, __gt__ and __ge__, so that <=, > and >= also work.