How does a Python set([]) check if two objects are equal? What methods does an object need to define to customise this? How does a Python set([]) check if two objects are equal? What methods does an object need to define to customise this? python python

How does a Python set([]) check if two objects are equal? What methods does an object need to define to customise this?


Yes, you need a __hash__()-method AND the comparing-operator which you already provided.

class Item(object):    def __init__(self, foo, bar):        self.foo = foo        self.bar = bar    def __repr__(self):        return "Item(%s, %s)" % (self.foo, self.bar)    def __eq__(self, other):        if isinstance(other, Item):            return ((self.foo == other.foo) and (self.bar == other.bar))        else:            return False    def __ne__(self, other):        return (not self.__eq__(other))    def __hash__(self):        return hash(self.__repr__())


I am afraid you will have to provide a __hash__() method. But you can code it the way, that it does not depend on the mutable attributes of your Item.