__cmp__ method is this not working as expected in Python 2.x?

cmp, python, python-2.x

Solution

`__cmp__(x,y)` should return a negative number (e.g. -1) if `x < y`, a positive number (e.g. 1) if `x > y` and 0 if `x == y`. You should never return a boolean with it.

What you're overloading is `__eq__(x, y)`.

Problem

``` class x: def __init__(self,name): self.name=name def __str__(self): return self.name def __cmp__(self,other): print("cmp method called with self="+str(self)+",other="+str(other)) return self.name==other.name # return False instance1=x("hello") instance2=x("there") print(instance1==instance2) print(instance1.name==instance2.name) ``` The output here is: ``` cmp method called with self=hello,other=there True False ``` Which is not what I expected: I'm trying to say 'two instances are equal if the name fields are equal'. If I simply `return False` from the `__cmp__` function, this reports as `True` as well!! If I return `-1`, then I get `False` - but since I'm trying to compare strings, this doesn't feel right. What am I doing wrong here?

Original source