For two objects a
and b
, __cmp__
requires that one of a < b
, a == b
, and a > b
is true. But that might not be the case: consider sets, where it’s very common that none of those are true, e.g. {1, 2, 3}
vs {4, 5, 6}
.
So __lt__
and friends were introduced. But that left Python with two separate ordering mechanisms, which is kind of ridiculous, so the less flexible one was removed in Python 3.
You don’t actually have to implement all six comparison methods. You can use the @total_ordering
decorator and only implement __lt__
and __eq__
.
edit: Also note that, in the case of sorting, key
functions can be more efficient than cmp
: in the example you gave, Python may have to call your Python comparison function O(n²) times. But a key
function only needs to be called O(n) times, and if the return value is then a builtin type (as it very often is), the O(n²) pairwise comparisons go through C.