The data model has been updated between python-2.x and python-3.x. In python-2.x one could use the __cmp__
method:
object.__cmp__(self, other)
Called by comparison operations if rich comparison (see above) is
not defined. Should return a negative integer if self < other
,
zero if self == other
, a positive integer if self > other
. If no __cmp__()
, __eq__()
or __ne__()
operation is defined,
class instances are compared by object identity ("address"). See
also the description of __hash__()
for some important notes on
creating hashable objects which support custom comparison operations
and are usable as dictionary keys. (Note: the restriction that
exceptions are not propagated by __cmp__()
has been removed since
Python 1.5.)
(formatting added)
The rich comparison operators are the __le__
, __ge__
, etc.. So in python-2.x there was an additional fallback mechanism. This is defined for an int
, as you can see with:
>>> (2).__cmp__
<method-wrapper '__cmp__' of int object at 0x13ee140>
>>> (2).__cmp__(3)
-1
(Python 2.7.12)
Furthermore python-2.x offers a cmp(..)
builtin function:
cmp(x, y)
Compare the two objects x
and y
and return an integer according to
the outcome. The return value is negative if x < y
, zero if x == y
and strictly positive if x > y
.
(formatting added)
In python-3.x, the __cmp__
has been removed as you can read in the What’s New In Python 3.0:
The cmp()
function should be treated as gone, and the __cmp__()
special method is no longer supported. Use __lt__()
for sorting,
__eq__()
with __hash__()
, and other rich comparisons as needed. (If you really need the cmp()
functionality, you could use the expression
(a > b) - (a < b)
as the equivalent for cmp(a, b)
.)
(formatting added)
This mechanism is not just a wrapper around __cmp__
: it will first look whether there are rich comparisons and if not fallback on __cmp__
itself.