Python total_ordering()
In Python, the total_ordering() decorator from the functools module simplifies the creation of fully ordered classes. By defining the __eq__() method and one additional comparison method (__lt__(), __le__(), __gt__(), or __ge__()), all other rich comparison methods are automatically generated.
This decorator reduces redundant code in custom classes that require complete ordering behavior for comparisons, sorting, and equality checks.
Syntax
from functools import total_ordering
@total_ordering
class ClassName:
def __eq__(self, other): ...
def __lt__(self, other): ...
Parameters:
The total_ordering() decorator takes no parameters.
Return value:
Returns a class with the missing comparison methods (__le__, __gt__, and __ge__) automatically added.
Example 1: Numeric Wrapper Class
The following example defines a class that compares wrapped numeric values. Only __eq__() and __lt__() are implemented; the rest are generated automatically:
from functools import total_ordering@total_orderingclass Number:def __init__(self, value):self.value = valuedef __eq__(self, other):return self.value == other.valuedef __lt__(self, other):return self.value < other.valueprint(Number(3) < Number(4))print(Number(5) >= Number(5))print(Number(7) > Number(1))
The outout of this code is:
TrueTrueTrue
Example 2: Ordering Strings by Length
This example demonstrates ordering based on string length instead of direct string comparison:
from functools import total_ordering@total_orderingclass Word:def __init__(self, text):self.text = textdef __eq__(self, other):return len(self.text) == len(other.text)def __lt__(self, other):return len(self.text) < len(other.text)print(Word("apple") < Word("banana"))print(Word("kiwi") == Word("pear"))print(Word("grape") > Word("fig"))
The output of this code is:
TrueTrueTrue
Codebyte Example: Prioritizing Tasks
The following codebyte defines a class where objects are ordered by priority value:
Higher priority numbers are treated as greater for sorting purposes.
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours