jamylak jamylak - 1 year ago 82
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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download