Re: adding elements to set



On Fri, Dec 9, 2011 at 3:34 AM, Andrea Crotti <andrea.crotti.0@xxxxxxxxx> 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
.



Relevant Pages

  • Re: Official definition of call-by-value (Re: Finding the instance reference...)
    ... consists of identity, type, and value. ... the intrinsic-value described above. ... I don't understand Python well enough to defend ... Who said the equality operator compares values ...
    (comp.lang.python)
  • Re: why () is () and [] is [] work in other way?
    ... comparison are disjoint operations, ... I call that "calling 'equality' something which shouldn't be regarded as such and making Python comply with it anyway." ... Conceptually, NaN is the class of all elements which are not numbers, therefore NaN = NaN. ...
    (comp.lang.python)
  • Re: why () is () and [] is [] work in other way?
    ... primitives and '==' as identity comparison for objects, ... exactly know how one would do that in Python. ... The equality operator can absolutely be used between two objects. ... Java does, I merely noted what it does. ...
    (comp.lang.python)
  • Re: Dictionary used to build a Triple Store
    ... It's about the Semantic Web BUT it uses python to build a "toy" triple store claimed to have good performance in the "tens of thousands" of triples. ... using the Python hash. ... Three hashes actually (I get that. ...
    (comp.lang.python)
  • Re: why () is () and [] is [] work in other way?
    ... primitives and '==' as identity comparison for objects, ... exactly know how one would do that in Python. ... It is as if Java tried to get rid of pointers but never completely succeeded in doing that. ... value equality defaults to identity equality but there are ...
    (comp.lang.python)