Python: Return NotImplemented from unsupported ordered comparisons
functools.total_ordering fills in ordered comparisons from equality and one ordering method. Those methods should return NotImplemented for unsupported operand types so Python can apply its normal comparison rules.
Tested on Linux with Python 3.12.14. Use Python 3.12 or newer. The example uses only the standard library and requires no network access.
Run the example
Save this as ordered_records_demo.py in an empty working directory:
from functools import total_ordering
@total_ordering
class Priority:
def __init__(self, rank):
self.rank = rank
def __eq__(self, other):
if not isinstance(other, Priority):
return NotImplemented
return self.rank == other.rank
def __lt__(self, other):
if not isinstance(other, Priority):
return NotImplemented
return self.rank < other.rank
low, high = Priority(1), Priority(3)
print("Less:", low < high)
print("At least:", high >= low)
print("Same rank:", low == Priority(1))
print("Other type equality:", low == 1)
try:
print(low < 1)
except TypeError:
print("Other type ordering rejected")Run it without -O so any assertions remain enabled:
python3 ordered_records_demo.pyCaptured output:
Less: True
At least: True
Same rank: True
Other type equality: False
Other type ordering rejectedNotImplemented is a return value, not an exception to raise. For equality with the integer, neither side supplies a matching comparison, so the result is false. Unsupported ordering raises TypeError instead of silently assigning a place to the integer.
Limits and cleanup
Define a consistent equality and order for your domain. The decorator does not validate that relationship or add hashing. Generated methods add overhead, so explicitly implement comparisons if profiling shows they matter. The example compares only these small in-memory records.
After testing, remove the example script from its working directory:
rm -- ordered_records_demo.pyReference
Acknowledgements
This post was created with assistance from AI.