Python 2.x has two ways to overload comparison operators, __cmp__
or the "rich comparison operators" such as __lt__
. The rich comparison overloads are said to be preferred, but why is this so?
Rich comparison operators are simpler to implement each, but you must implement several of them with nearly identical logic. However, if you can use the builtin cmp
and tuple ordering, then __cmp__
gets quite simple and fulfills all the comparisons:
class A(object):
def __init__(self, name, age, other):
self.name = name
self.age = age
self.other = other
def __cmp__(self, other):
assert isinstance(other, A) # assumption for this example
return cmp((self.name, self.age, self.other),
(other.name, other.age, other.other))
This simplicity seems to meet my needs much better than overloading all 6(!) of the rich comparisons. (However, you can get it down to "just" 4 if you rely on the "swapped argument"/reflected behavior, but that results in a net increase of complication, in my humble opinion.)
Are there any unforeseen pitfalls I need to be made aware of if I only overload __cmp__
?
I understand the <
, <=
, ==
, etc. operators can be overloaded for other purposes, and can return any object they like. I am not asking about the merits of that approach, but only about differences when using these operators for comparisons in the same sense that they mean for numbers.
Update: As Christopher pointed out, cmp
is disappearing in 3.x. Are there any alternatives that make implementing comparisons as easy as the above __cmp__
?