total ordering

suggest change

When we want to create an orderable class, normally we need to define the methods __eq()__, __lt__(), __le__(), __gt__() and __ge__().

The total_ordering decorator, applied to a class, permits the definition of __eq__() and only one between __lt__(), __le__(), __gt__() and __ge__(), and still allow 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 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 simply check not __lt__() and not __eq()__.

Note: The total_ordering function is only available since Python 2.7.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents