cmp() on integers - is there guarantee of returning only +-1 or 0?

wittempj@hotmail.com martin.witte at gmail.com
Sun Mar 19 17:38:51 EST 2006


It is depending on the classes you try to compare, and on how the
comparison functions (see
http://docs.python.org/ref/customization.html) are implemented in
these, see example below:

py> class wrong(object):
...     def __init__(self, x):
...         self.x = x
...     def __cmp__(self, other):
...         if self.x < other.x:
...             return -1
...         else:
...             return 1
...
py> class right(object):
...     def __init__(self, x):
...         self.x = x
...     def __cmp__(self, other):
...         if self.x < other.x:
...             return -1
...         elif self.x > other.x:
...             return 1
...         else:
...             return 0
...
py> w1 = wrong(1)
py> w2 = wrong(1)
py> cmp(w1, w2)
1
py>
py> r1 = right(1)
py> r2 = right(1)
py> cmp(r1, r2)
0




More information about the Python-list mailing list