Problem comparing object graphs and trees

R

raphael.marvie

Dear all,

I am trying to compare graphes of object through the use of the __cmp__
operator. Before managing the problem of recursive comparison, I have
tried a simple test which result surprises me. Here is the simplest
code I can write that presents my problem:

</pre>
$ cat cmp.py

class A:
def __init__(self, b):
self.b = b
def __cmp__(self, other):
return self.b == other.b

class B:
pass

if __name__ == '__main__':
b = B()
a1 = A(b)
a2 = A(b)
print a1 == a2
print a1 == a1

$ python cmp.py
False
False
</pre>

I swear I am not drunk, but why isn't a1 == a2 and worse why isn't a1
== a1? Does someone have a clue and can explain to me this suprising
behavior? (python 2.4.3 on Ubuntu 6.06).

Cheers,

r.
 
P

Peter Otten

</pre>
$ cat cmp.py

class A:
def __init__(self, b):
self.b = b
def __cmp__(self, other):
return self.b == other.b

class B:
pass

if __name__ == '__main__':
b = B()
a1 = A(b)
a2 = A(b)
print a1 == a2
print a1 == a1

$ python cmp.py
False
False
</pre>

I swear I am not drunk, but why isn't a1 == a2 and worse why isn't a1
== a1? Does someone have a clue and can explain to me this suprising
behavior? (python 2.4.3 on Ubuntu 6.06).

__cmp__() must return 0 for equal objects:
(1, 0, -1)

You might have a look at rich comparison before you proceed:
.... def __init__(self, b):
.... self.b = b
.... def __eq__(self, other):
.... return self.b == other.b
....False

Peter
 
D

Duncan Booth

I swear I am not drunk, but why isn't a1 == a2 and worse why isn't a1
== a1? Does someone have a clue and can explain to me this suprising
behavior? (python 2.4.3 on Ubuntu 6.06).

Because the __cmp__ method doesn't return a boolean. It returns a value <0,
0 or >0 according to the relative ordering of its arguments. You are
returning True (1) when the values are equal and you should be returning 0.

If ordering isn't defined for your objects then define __eq__ instead of
__cmp__.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top