By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,222 Members | 2,374 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,222 IT Pros & Developers. It's quick & easy.

Deep comparison of sets?

P: n/a
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?

--
Daryl Spitzer
Nov 7 '07 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Daryl Spitzer schrieb:
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
Nov 7 '07 #2

P: n/a
On Wed, 07 Nov 2007 10:22:27 -0800, Daryl Spitzer wrote:
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
Nov 7 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.