Consider this snippet:
class SomeClass(object):
def __init__(self, someattribute="somevalue"):
self.someattribute = someattribute
def __eq__(self, other):
return self.someattribute == other.someattribute
def __ne__(self, other):
return not self.__eq__(other)
list_of_objects = [SomeClass()]
print(SomeClass() in list_of_objects)
set_of_objects = set([SomeClass()])
print(SomeClass() in set_of_objects)
which evaluates to:
True
False
Can anyone explain why the ‘in’ keyword has a different meaning for sets and lists?
I would have expected both to return True, especially when the type being tested has equality methods defined.
The meaning is the same, but the implementation is different. Lists simply examine each object, checking for equality, so it works for your class. Sets first hash the objects, and if they don’t implement hash properly, the set appears not to work.
Your class defines
__eq__, but doesn’t define__hash__, and so won’t work properly for sets or as keys of dictionaries. The rule for__eq__and__hash__is that two objects that__eq__as True must also have equal hashes. By default, objects hash based on their memory address. So your two objects that are equal by your definition don’t provide the same hash, so they break the rule about__eq__and__hash__.If you provide a
__hash__implementation, it will work fine. For your sample code, it could be: