Search code examples
python-3.xsortingredefinition

Which Python object comparison methods to redefine to make sorted() work?


I feel this question must have been asked before but I could not find an answer.

Suppose I want to implement a Python class whose objects are sortable with sorted(). Do I have to reimplement all methods like __lt__(), __gt__(), etc.? What is the bare minimum? In other words, which method(s) does sorted() call for sorting?


Solution

  • Per the documentation:

    sort(*, key=None, reverse=False)
    This method sorts the list in place, using only < comparisons between items. Exceptions are not suppressed - if any comparison operations fail, the entire sort operation will fail (and the list will likely be left in a partially modified state).

    So you only need to define def __lt__(self,other): for your class.

    Also see the Sorting HOW-TO which says near the bottom:

    The sort routines are guaranteed to use __lt__() when making comparisons between two objects. So, it is easy to add a standard sort order to a class by defining an __lt__() method: