Sets and Membership Tests

Alex Martelli aleax at mac.com
Wed Jul 12 10:34:37 EDT 2006


JKPeck <JKPeck at gmail.com> wrote:

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

Your problem may have been exactly that you were misunderstanding the
nature and functionality of object.__hash__:

>>> x='guess what'
>>> id(x)
360720
>>> object.__hash__(x)
360720

As you see, what it does is return the id() of the object (that's how
objects are hashed -- if they don't implement __eq__ or __cmp__,
equality comparisons also go to the id()'s, so things work;-) -- unless
their type/class overrides __hash__).  Of course, by going directly to
object.__hash__ you're explicitly *avoiding* the override, so...


Alex



More information about the Python-list mailing list