Sets and Membership Tests

JKPeck JKPeck at gmail.com
Wed Jul 12 10:12:01 EDT 2006


Thanks for the advice.  Once assured that __hash__ etc was the right
route, I found that using hash() instead of object.__hash__() gave me
stable hash valules.  (I am hashing strings that I know to be unique.)

The "no luck" situation was that a set would accept the same object
multiple times, not recognizing that it was truly the same object.


Nick Vatamaniuc wrote:
> JK,
>
> You are correct to implement __hash__ and __eq__. The problem is how
> you implemented them. Usually your __eq__ method should compare the
> necessary attributes of the objects for equality. The __hash__ should
> return a 32-bit integer. Your best bet is probably to return a hash of
> hashes of your attributes that are used in equality comparison. What
> this means is that your attributes used to produce the __hash__ should
> also be hashable. This is important yet not immediatly obvious. So you
> could for example return hash( (attribute1, attribute2, attribute3) ),
> where attribute1, attribute2, attribute3 are all hashable.
>  Of course, you provided no code and no error messages (the
> 'SoFarNoLuck' exception is not descriptive enough ; )
>
> Hope this helps
>
>
>
> JKPeck wrote:
> > I would like to be able use sets where the set members are objects of a
> > class I wrote.
> > I want the members to be distinguished by some of the object content,
> > but I have not figured out how a set determines whether two (potential)
> > elements are identical.  I tried implementing __eq__ and __ne__ and
> > __hash__ to make objects with identical content behave as identical for
> > set membership, but so far no luck.
> >
> > I could subclass set if necessary, but I still don't know what I would
> > need to override.
> > 
> > TIA for any advice you can offer.




More information about the Python-list mailing list