jamylak jamylak - 13 days ago 5x
Python Question

Python 2.x return values for cmp

Quoted from the docs:

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

I was under the assumption that the return values are always
, and
but the docs don't explicitly say that, only mentioning zero and positive/negative return value.

Are there any situations when the return value of
is not
, or


No, the docs explicitly say that yalues can be anything. The only value that is specified is 0 if the compared objects are equal. Don't trust the fact that you only see the values -1, 0 and 1, that's an implementation detail and could change*, so always check for < and > 0.

*: note - actually, it won't really have a chance to change, since cmp has gone away in pyhton3. use rich comparison instead.