Deep comparison of sets?

Diez B. Roggisch deets at nospam.web.de
Wed Nov 7 13:29:17 EST 2007


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



More information about the Python-list mailing list