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.
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
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.
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
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()andlist.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 usefunctools.total_ordering(which needs__eq__()and one of the four).- Compare tuples of key fields instead of chaining
ifstatements:(self.last, self.first) < (other.last, other.first). - Return
NotImplementedfor foreign types so mixed comparisons produce a clearTypeErrorinstead of a wrong answer. - Consistent with
__eq__. Ordering that disagrees with equality (for examplea <= bandb <= awhilea != b) confuses sorting andbisect. - 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_orderingis slower than hand-written methods; it matters only in hot loops.
Related
__eq__() and __hash__(),sorted(),max(),min(),functools- Lessons: Special methods, Data classes