[Python-3000] __hash__ : Problem with either documentation or understanding

Chris Rebert cvrebert at gmail.com
Wed Jul 30 00:31:38 CEST 2008

Your question isn't really Python-3000-specific, and belongs more on
the comp.lang.python list.

That said, whether it's right for your object really depends on how
you're defining equality for it. Are you defining equality as merely
identity (i.e. are they pointers to the same spot in memory) or does
it depend on the values of their instance variables?
If the former, then your approach is fine, and in fact Python's
default __hash__ does something similar by default using id(), so you
don't even need to implement your own __hash__; just use the default
one from class object.
If the latter, than you shouldn't implement __hash__ because, as the
docs you quote say, Bad Things (tm) will happen if someone puts your
object into a dict and then mutates it.
So really it comes down to answering the question: "Can mutating an
instance of my class affect its equality with other instances?"
I can't answer it for you since you didn't include enough information
about your exact circumstances, but you should be able to answer it
for yourself.

Hope that helps to elucidate it for you. And remember to post to the
correct mailinglist n the future.

- Chris

Follow the path of the Iguana...
Rebertia: http://rebertia.com
Blog: http://blog.rebertia.com

On Tue, Jul 29, 2008 at 3:13 PM, Charles Hixson
<charleshixsn at earthlink.net> wrote:
> .../Python-3.0b2/Python-3.0b2/Doc/build/html/reference/datamodel.html#object.__hash__
> """If a class defines mutable objects and implements a __cmp__() or __eq__()
> method, it should not implement __hash__(), since the dictionary
> implementation requires that a key's hash value is immutable (if the object's
> hash value changes, it will be in the wrong hash bucket).
> """
> What I had been planning to do was implement a hash code created by hashing a
> unique integer, say the sequential order in which the instance of the class
> was created.  This would be unique and unchanging number, so the explanation
> of why __hash__ should not be created seems wrong.  Or *could* it be created?
> In which case that statement that it shouldn't be created is wrong.
> (Or, of course, I'm misunderstanding things.)
> _______________________________________________
> Python-3000 mailing list
> Python-3000 at python.org
> http://mail.python.org/mailman/listinfo/python-3000
> Unsubscribe: http://mail.python.org/mailman/options/python-3000/cvrebert%40gmail.com

More information about the Python-3000 mailing list