How does functools.total_ordering reduce boilerplate for comparison methods?
Short answer
total_ordering takes a class that defines __eq__ and one of __lt__, __le__, __gt__, or __ge__, then fills in the remaining comparison methods automatically. This avoids manually writing all six rich comparison methods for classes that need full ordering support.
Advertisement
AModel answer
total_ordering takes a class that defines __eq__ and one of __lt__, __le__, __gt__, or __ge__, then fills in the remaining comparison methods automatically. This avoids manually writing all six rich comparison methods for classes that need full ordering support.
from functools import total_ordering
@total_ordering
class Version:
def __init__(self, num):
self.num = num
def __eq__(self, other):
return self.num == other.num
def __lt__(self, other):
return self.num < other.num
print(Version(1) <= Version(2)) # True, auto-derivedReal-world example
A package manager's Version class uses total_ordering to support sorting release versions without writing __le__, __gt__, and __ge__ by hand.
Likely follow-ups
- Why is total_ordering slower than writing all methods manually?
- What happens if __eq__ is missing?
Related topics