Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Classes and Special Methods

__lt__() and ordering methods

Reference for Python __lt__, __le__, __gt__, __ge__: making objects sortable, reflected comparisons, functools.total_ordering and dataclass order=True.

Four methods define the ordering operators: __lt__() for <, __le__() for <=, __gt__() for > and __ge__() for >=. Together with __eq__() and __ne__() they are called the rich comparison methods.

To sort objects with sorted(), list.sort(), min() or max(), defining __lt__() is enough: sorting only uses <. To support all four operators with little code, define __eq__() and one ordering method and add functools.total_ordering.

Python
class Version:
    def __init__(self, major, minor):
        self.major, self.minor = major, minor
    def __lt__(self, other):
        return (self.major, self.minor) < (other.major, other.minor)

Try it

Python Sorting custom objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python total_ordering and dataclasses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
class C:
    def __lt__(self, other): ...   # self <  other
    def __le__(self, other): ...   # self <= other
    def __gt__(self, other): ...   # self >  other
    def __ge__(self, other): ...   # self >= other
Operator Method Reflected (tried on other if the first returns NotImplemented)
a < b a.__lt__(b) b.__gt__(a)
a <= b a.__le__(b) b.__ge__(a)
a > b a.__gt__(b) b.__lt__(a)
a >= b a.__ge__(b) b.__le__(a)

Return value: normally a bool, or NotImplemented when the other type is unsupported.

Raises: TypeError ("not supported between instances") when both sides return NotImplemented or a method is missing.

Usage notes

  • Sorting needs only <. sorted() and list.sort() call __lt__(); that is why the first example works without the other three.
  • Reflection helps. Version(1, 1) > Version(1, 0) works with only __lt__() defined, because Python falls back to the reflected __lt__() of the right-hand operand.
  • <= is not derived from < and == automatically. Define it, or use functools.total_ordering (which needs __eq__() and one of the four).
  • Compare tuples of key fields instead of chaining if statements: (self.last, self.first) < (other.last, other.first).
  • Return NotImplemented for foreign types so mixed comparisons produce a clear TypeError instead of a wrong answer.
  • Consistent with __eq__. Ordering that disagrees with equality (for example a <= b and b <= a while a != b) confuses sorting and bisect.
  • A key function is often simpler. sorted(items, key=lambda v: (v.major, v.minor)) needs no methods at all, and you can sort by different rules in different places.
  • @dataclass(order=True) compares instances field by field in declaration order, as tuples.
  • total_ordering is slower than hand-written methods; it matters only in hot loops.