cmp

Jeff Shannon jeff at ccvcorp.com
Thu Dec 27 20:22:15 CET 2001


Matt Russell wrote:

> Well, I just made myself look silly. I admit it...
>
> when I type 1==1 into the interpreter, I thought if it was true, the
> result is 1 -  this is right. But cmp(1,1) actually returns 0 (in
> accordance to the docs)
>
> But why then are we given the mechanism to compare instances of
> classes via the __cmp__ def ?
>
> Collegues of mine have used this to return 1 (truth) if two instances
> are equal (instanceA==instanceB).... this obviously wasn't the
> intended purpose. (__cmp__ shuold return 0 if the result of cmp(a,b)
> is to be trusted??
>
> Perhaps then could someone explain to me how one compares classes
> useing the == operator, or indeed if this bad programming practice.
>
> I hope I didn't waste too much of guido's time when I posted a bug on
> sourceforge :(

cmp(a, b) is not a boolean function, as your colleagues apparently feel
it should be.  It's actually a trinary function--it can return -1, 0, or
+1, representing a being less than, equal to, or greater than b,
respectively.

Comparing classes with the == operator is fine.  If you've declared a
__cmp__() for your class, then == will use that.  If you haven't, then ==
uses 'is' -- in other words, it tests for object identity.

Note that if cmp(a, b) returns 0, then a == b will evaluate to 1.

>>> class test:
...  def __init__(self, val):
...   self.value = val
...  def __cmp__(self, other):
...   try:
...    return cmp(self.value, other.value)
...   except:
...    return -1
...
>>> a = test(1)
>>> b = test(2)
>>> c = test(2)
>>> a < b
1
>>> b is c
0
>>> b == c
1
>>>

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list