How to use functools.total_ordering in Python

@functools.total_ordering class decorator in Python supplies comparison ordering methods for a given class, provided the given class satisfies below conditions.

  • Given class should define __eq__() method.
  • Given class must define any one of __lt__(), __le__(), __gt__(), or __ge__() methods.

lets understand this with below example, where class Student implements __eq__() and __lt__ comparison method and rest of the comparison ordering methods are being supplied by @functools.total_ordering class decorator.

Create Student Class
            
from functools import total_ordering

@total_ordering
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def _is_valid_operand(self, other):
        return hasattr(other, "name") and hasattr(other, "age")

    def __eq__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return self.age == other.age

    def __lt__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return self.age < other.age
        
    
Create instances of Student class
           
student1 = Student("xyz", 23)
student2 = Student("abc", 25)

Use comparison operators on class instances
          
print(student1 == student2)
print(student1 > student2)
print(student1 < student2)

# Output
False
False
True