total ordering
suggest changeWhen we want to create an orderable class, normally we need to define the methods __eq__(), __lt__(), __le__(), __gt__(), and __ge__().
The functools.total_ordering decorator, applied to a class, permits the definition of __eq__() and only one of __lt__(), __le__(), __gt__(), and __ge__(), and still allows all the ordering operations on the class.
@total_ordering
class Employee:
...
def __eq__(self, other):
return ((self.surname, self.name) == (other.surname, other.name))
def __lt__(self, other):
return ((self.surname, self.name) < (other.surname, other.name))
The ... body does not set surname or name, so this class does not run as written. The decorator uses a composition of the provided methods and algebraic operations to derive the other comparison methods. For example, if we defined __lt__() and __eq__() and we want to derive __gt__(), we can check not __lt__() and not __eq__().
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents