Python › functools & Functional Programming Tools
How does functools.total_ordering reduce boilerplate for comparison methods?
IntermediateAnswer
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.