Re: Overloading the comparison operator
Tue, 24 May 1994 08:58:12 +0200

> According to the documentationI have, one overloads == and != by
> defining __cmp__ in a class definition. Unfortunately, the is the (to
> me) undesirable side effect of also overloading <, <=, >, and >=.
> There are (non-magnitude) classes for which one would like to override
> ==, and !=, but not <, <=, >, and >=. Is there a way to do this? Is
> something planned?

No, unfortunately for you, in Python all six types of comparisons are
tied together. When you decide that two objects are not equal, your
__cmp__ method will have to make an arbitrary decision about which one
to call "smaller". Tell your users that using < etc. is unwise on the
type you have defined. For certain operations it might still be
useful to try and define < consistently so that if a<b and b<c, a<c
is true. This is needed when e.g. a list of such objects gets
accidentally sorted.

Note that the same is true for all Python types -- in many cases the
comparison operator simply compares the address of two objects
(e.g. try comparing classes).

--Guido van Rossum, CWI, Amsterdam <>
URL: <>