Python: Behavior of object in set operations

Posted by Josh Arenberg on Stack Overflow See other posts from Stack Overflow or by Josh Arenberg
Published on 2010-04-07T18:28:15Z Indexed on 2010/04/07 18:33 UTC
Read the original article Hit count: 155

Filed under:
|
|

I'm trying to create a custom object that behaves properly in set operations.

I've generally got it working, but I want to make sure I fully understand the implications. In particular, I'm interested in the behavior when there is additional data in the object that is not included in the equal / hash methods. It seems that in the 'intersection' operation, it returns the set of objects that are being compared to, where the 'union' operations returns the set of objects that are being compared.

To illustrate:

class MyObject:
    def __init__(self,value,meta):
        self.value = value
        self.meta = meta
    def __eq__(self,other):
        if self.value == other.value:
            return True
        else:
            return False
    def __hash__(self):
        return hash(self.value)

a = MyObject('1','left')
b = MyObject('1','right')
c = MyObject('2','left')
d = MyObject('2','right')
e = MyObject('3','left')
print a == b # True
print a == c # False

for i in set([a,c,e]).intersection(set([b,d])):
    print "%s %s" % (i.value,i.meta)
#returns:
#1 right
#2 right

 for i in set([a,c,e]).union(set([b,d])):
    print "%s %s" % (i.value,i.meta)
#returns:
#1 left
#3 left
#2 left

Is this behavior documented somewhere and deterministic? If so, what is the governing principle?

© Stack Overflow or respective owner

Related posts about python

Related posts about set