“Enabling” comparison for classes [duplicate]

You can use the total_ordering decorator from functools, which generates all the missing compare methods if you supply __eq__() and one other.

Given a class defining one or more
rich comparison ordering methods, this
class decorator supplies the rest.
This simplifies the effort involved in
specifying all of the possible rich
comparison operations:

The class must define one of __lt__(),
__le__(), __gt__(), or __ge__(). In addition, the class should supply an
__eq__() method.

For Example,

import functools


@functools.total_ordering
class Student:
    def _is_valid_operand(self, other):
        return (hasattr(other, "lastname") and
                hasattr(other, "firstname"))

    def __eq__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return ((self.lastname.lower(), self.firstname.lower()) ==
                (other.lastname.lower(), other.firstname.lower()))

    def __lt__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return ((self.lastname.lower(), self.firstname.lower()) <
                (other.lastname.lower(), other.firstname.lower()))

Leave a Comment