In this lesson, you will learn how to use the total_ordering decorator to automatically generate a full suite of comparison methods for your classes by defining only two of them.
The Problem of Boilerplate
When you want your custom objects to be comparable using operators like >, <, >=, or <=, you usually have to define each corresponding special method (__gt__, __lt__, __ge__, __le__). Writing out all six methods (including equality __eq__) is tedious and prone to typos, especially since these methods are mathematically related—for example, if a > b is true, then b < a must also be true.
Introducing total_ordering
Python provides a elegant solution in the functools module called @total_ordering. By decorating your class with it, you only need to implement two methods:
__eq__(to handle equality)- One of the ordering methods (like
__lt__,__le__,__gt__, or__ge__)
The decorator uses the logic you provided to "fill in the blanks" for the remaining comparison methods automatically.
Practical Example
Imagine a class representing a Book ranked by its page count:
from functools import total_ordering
@total_ordering
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def __eq__(self, other):
return self.pages == other.pages
def __lt__(self, other):
return self.pages < other.pages
# Now we can compare books easily!
b1 = Book("Python Basics", 200)
b2 = Book("Advanced OOP", 400)
print(b1 < b2) # True
print(b2 >= b1) # True (Automatically generated!)
By defining how objects are equal and how one is "less than" another, the @total_ordering decorator provides the rest of the logic, keeping your code clean and dry. You no longer need to manually write six different methods just to allow your objects to be sorted or compared.
Key Takeaway: The @total_ordering decorator minimizes code duplication by automatically generating missing comparison methods based on your implementation of __eq__ and a single ordering method.