adding elements to set

Chris Angelico rosuav at gmail.com
Thu Dec 8 11:47:24 EST 2011


On Fri, Dec 9, 2011 at 3:34 AM, Andrea Crotti <andrea.crotti.0 at gmail.com> wrote:
> I've wasted way too much time for this, which is surely not a Python bug,
> not something that surprised me a lot.
>
> I stupidly gave for granted that adding an object to a set would first
> check if there are equal elements inside, and then add it.

It checks for equality using hashes. By default, in Python 2, objects'
hashes are their ids - meaning that no two of them hash alike, and
you'll get duplicates in your set. (In Python 3, the default appears
to be that they're unhashable and hence can't go into the set at all.)

class C(object):

   def __init__(self, x):
       self.x = x

   def __eq__(self, other):
       return self.x == other.x

   def __hash__(self):
       return hash(self.x)

This chains the hashing requirement to the child, just as it chains
the equality check. You can then stuff your objects into a set with
more expected results.

ChrisA



More information about the Python-list mailing list