The total_ordering()
function in the functools
module is a decorator that is used to simplify the implementation of classes that need to support rich comparison operations (i.e., __lt__
, __gt__
, __le__
, __ge__
, __eq__
, __ne__
). The six comparison methods are used for implementing the internal workings of the comparison operators as shown below.
method | operator | name |
---|---|---|
__lt__ |
< |
less than |
__gt__ |
> |
greater than |
__le__ |
<= |
less than or equal to |
__ge__ |
>= |
greater then or equal to |
__eq__ |
== |
equal |
__ne__ |
!= |
not equal |
How the total_ordering decorator works
The @total_ordering()
function performs a number of checks to make sure that implementations are consistent and correct. The only conditions is that the target class should:
- define
__eq__()
method. - define any one of
__lt__(), __le__(), __gt__(), or __ge__()
methods.
When the two conditions are met, the function automatically fills in the missing methods.
@total_ordering
class class_to_decorate
#statements
def __eq__(self, other):
#statements
def __gt__(self, other):
#statements
from functools import total_ordering
@total_ordering
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
return (self.name, self.age) == (other.name, other.age)
def __lt__(self, other):
return self.age < other.age
p1 = Person('John', 20)
p2 = Person('Mike', 30)
print(p1 < p2)
print(p1 > p2)
print(p1 <= p2)
print(p1 >= p2)
print(p1 == p2)
print(p1 != p2)