Python functools total_ordering() Function
The Python total_ordering() function decorator from the functools module simplifies the implementation of all comparison methods. The functools module is designed to specify the higher-order functions, and the total ordering decorator is a prime example. It enhances the class capabilities without requiring explicit definitions for each comparison method, making the code more maintainable and efficient.
Syntax
Following is the syntax for the total_ordering() function.
@total_ordering()
Parameters
This function doesn't accept any parameters.
Return Value
The decorator returns the class with the additional comparison methods like (__le__, __gt__, __ge__).Below example demosntr
Example 1
The example below, demonstrates a class with methods like __le__, __gt__ and __ge__, which are automatically provided by the total_ordering decorator.
from functools import total_ordering
@total_ordering
class Num:
def __init__(self, val):
self.val = val
def __eq__(self, other):
return self.val == other.val
def __lt__(self, other):
return self.val < other.val
print(Num(31) < Num(12))
print(Num(200) > Num(101))
print(Num(56) == Num(18))
print(Num(2) != Num(2))
Output
The result is generated as follows −
False True False False
Example 2
In this example, the total_ordering() decorator compares word object on the length of their text. By defining the __eq__ and __it__ methods, it automatically provides other comparison methods,simplifying the comparison logic.
from functools import total_ordering
@total_ordering
class Word:
def __init__(self, txt):
self.txt = txt
def __eq__(self, other):
return len(self.txt) == len(other.txt)
def __lt__(self, other):
return len(self.txt) < len(other.txt)
print(Word("grapes") < Word("watermelon"))
print(Word("banana") < Word("kiwi"))
print(Word("pineapple") == Word("grape"))
Output
The code is generated as follows −
True False False
Example 3
We are now creating a code that defines a point class with n and p coordinates. Using the total_ordering() decorator, function simplifies the code by defining the __eq__ and __lt__ methods. The decorator allows easy comparison of point objects based on their coordinates.
from functools import total_ordering
@total_ordering
class Point:
def __init__(self, n, p):
self.n = n
self.p = p
def __eq__(self, other):
return (self.n, self.p) == (other.n, other.p)
def __lt__(self, other):
return (self.n, self.p) < (other.n, other.p)
print(Point(31, 4) < Point(21, 11))
print(Point(10, 12) > Point(0, 13))
print(Point(2, 2) == Point(1, 1))
Output
The output is obtained as follows −
False True False
python_modules.htm