Deep comparison of sets?

D

Daryl Spitzer

The second assertion in the following code fails:

class Value(object):
def __init__(self, value):
super(Value, self).__init__()
self.value = value
def __cmp__(self, other):
if self.value > other.value: return 1
if self.value < other.value: return -1
return 0

if __name__ == "__main__":
v1 = Value('one')
v2 = Value('one')
assert v1 == v2
s1 = set([v1])
s2 = set([v2])
assert s1 == s2

Is there any way to compare the two sets so that __cmp__ is called (I
guess this would be called a deep comparison) rather than just
(shallowly) comparing each object in the set?
 
D

Diez B. Roggisch

Daryl said:
The second assertion in the following code fails:

class Value(object):
def __init__(self, value):
super(Value, self).__init__()
self.value = value
def __cmp__(self, other):
if self.value > other.value: return 1
if self.value < other.value: return -1
return 0

if __name__ == "__main__":
v1 = Value('one')
v2 = Value('one')
assert v1 == v2
s1 = set([v1])
s2 = set([v2])
assert s1 == s2

Is there any way to compare the two sets so that __cmp__ is called (I
guess this would be called a deep comparison) rather than just
(shallowly) comparing each object in the set?

You need to overload the __hash__-method as well.

def __hash__(self):
return hash(self.value)


Diez
 
M

Marc 'BlackJack' Rintsch

def __cmp__(self, other):
if self.value > other.value: return 1
if self.value < other.value: return -1
return 0

This can be written a bit shorter::

def __cmp__(self, other):
return cmp(self.value, other.value)

Ciao,
Marc 'BlackJack' Rintsch
 

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

No members online now.

Forum statistics

Threads
473,989
Messages
2,570,207
Members
46,783
Latest member
RickeyDort

Latest Threads

Top