Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python rich comparison: return NotImplemented for unsupported operands

Last updated: 30 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

NotImplemented tells Python that a comparison method does not implement the supplied operand pair, allowing reflected comparison or the normal fallback.

Download Python source kit

Operation contract

The receipt rank compares only another rank from the same domain. Unsupported values receive NotImplemented rather than false or an arbitrary ordering. total_ordering supplies the other ordering methods from equality and less-than. Equality with an unrelated integer falls back to false, while ordering the same pair raises TypeError. These results are intentional: inequality does not grant a meaningful cross-type order.

Failure and ownership boundary

A rank object should not change its ordering fields while retained inside a sorted structure. This teaching class exposes a simple field and therefore requires caller discipline; use an immutable representation at a public boundary. Returning false for every unrelated comparison can hide mistakes and violate sorting assumptions. Python hash and equality: immutable dictionary keys, Python sorting: stable keys, independent output and explicit tie rules and Python bisect: binary position search does not make list insertion logarithmic depend on a consistent contract.

Working program

python
from functools import total_ordering

@total_ordering
class ReceiptRank:
    def __init__(self, priority):
        if type(priority) is not int or not 0 <= priority <= 9:
            raise ValueError("priority bound")
        self.priority = priority
    def __eq__(self, other):
        if type(other) is not ReceiptRank:
            return NotImplemented
        return self.priority == other.priority
    def __lt__(self, other):
        if type(other) is not ReceiptRank:
            return NotImplemented
        return self.priority < other.priority

print("ordered:", ReceiptRank(2) < ReceiptRank(4))
print("unrelated equal:", ReceiptRank(2) == 2)
print("method fallback:", ReceiptRank(2).__lt__(2) is NotImplemented)
try:
    ReceiptRank(2) < 2
except TypeError:
    print("unrelated ordering rejected")

Output

Output
ordered: True
unrelated equal: False
method fallback: True
unrelated ordering rejected

Costs and limits

Each bounded-priority comparison has fixed scalar work. Generated methods can invoke several underlying comparisons rather than performing one primitive operation. This class is unhashable after defining equality; do not add a hash that disagrees with equality.

Common Mistakes

  • NotImplemented is a result, not the NotImplementedError exception.
  • Returning false is not the same as declining an unsupported comparison.

Connected lessons

Python hash and equality: immutable dictionary keys, Python sorting: stable keys, independent output and explicit tie rules, Python bisect: binary position search does not make list insertion logarithmic.

python
ordering-protocol
Storage details