What is the total_ordering descriptor in functools in Python?

Functools module

The functools module in Python creates higher-order functions that interact with other functions. The higher-order functions either return other functions, or operate on them to broaden the scope of the function without modifying or explicitly defining them.

Comparison ordering methods of a class

Comparison ordering methods of a class are used for the comparison of class objects. There are six comparison ordering methods for any given class. They are as follows:

  • __lt__(): Lesser than method
  • __le__(): Lesser than or equal to method
  • __gt__(): Greater than method
  • __ge__(): Greater than or equal to method
  • __eq__(): Equal to method

total_ordering descriptor

Let’s imagine that we need to compare class objects. Hence, we have to provide the implementations of all the comparison ordering methods of the class. This requires a bit of effort.

However, we can simplify the process with the total_ordering descriptor. We can define any one of the comparison ordering methods, and the decorator supplies the rest of the methods. The class also must provide an __eq__() method.

Let’s consider we supply the __lt__ and __eq__ methods. The decorator supplies the rest of the comparison methods i.e., __le__(), __gt__(), and __ge__().

Code

from functools import total_ordering
@total_ordering
class Person:
def __init__(self, age):
self.age = age
def __lt__(self, other):
return self.age < other.age
def __eq__(self, other):
return self.age == other.age
person1 = Person(10)
person2 = Person(20)
print("Person(10) > Person(20) ? ", person1 > person2)
print("Person(10) == Person(20) ? ", person1 == person2)
print("Person(10) >= Person(20) ? ", person1 >= person2)
print("Person(10) < Person(20) ? ", person1 < person2)
print("Person(10) <= Person(20) ? ", person1 <= person2)

Explanation

  • Line 1: We import the total_ordering decorator.
  • Lines 3 to 13: We define a Person class decorated with total_ordering. The class has age as an attribute. We provide the implementations for the __lt__() and __eq__() methods considering the age attribute.
  • Lines 15 to 16: We define two Person objects called person1 and person2, with a different value for the age attributes of each.
  • Lines 17 to 21: We compare person1 and person2 using different comparison operators.

Free Resources