Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I need to create a 'container' object or class in Python, which keeps a record of other objects which I also define. One requirement of this container is that if two objects are deemed to be identical, one (either one) is removed. My first thought was to use a set([]) as the containing object, to complete this requirement.

However, the set does not remove one of the two identical object instances. What must I define to create one?

Here is the Python code.

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)) 

Interpreter

>>> set([Item(1,2), Item(1,2)]) set([Item(1, 2), Item(1, 2)]) 

It is clear that __eq__(), which is called by x == y, is not the method called by the set. What is called? What other method must I define?

Note: The Items must remain mutable, and can change, so I cannot provide a __hash__() method. If this is the only way of doing it, then I will rewrite for use of immutable Items.

like image 826
Ada Avatar asked Oct 15 '10 12:10

Ada


People also ask

How does Python check if two objects are equal?

The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and != , except when you're comparing to None .

How do you check for equality in Python?

Python strings equality can be checked using == operator or __eq__() function. Python strings are case sensitive, so these equality check methods are also case sensitive.

What is __ eq __ method in Python?

Summary. Implement the Python __eq__ method to define the equality logic for comparing two objects using the equal operator ( == )


1 Answers

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__()) 
like image 150
ruena Avatar answered Sep 24 '22 00:09

ruena