Python functools - total_ordering()
Python tip:
You can create an orderable class (assuming the type is totally ordered) with
__eq__
, one other comparison methods (__ne__
,__lt__
,__le__
,__gt__
,__ge__
), and thetotal_ordering
decorator.An example👇
from functools import total_ordering @total_ordering class Sample: def __init__(self, value): self.value = value def __lt__(self, other): return self.value < other.value x = Sample(3) y = Sample(4) for expression in ["x == y", "x != y", "x < y", "x <= y", "x > y", "x >= y"]: result = eval(expression) print(f"{expression} is {result}") """ x == y is False x != y is True x < y is True x <= y is True x > y is False x >= y is False """
Without it, you'd need to define all of the comparison methods.