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

Jim Jewett jimjjewett at gmail.com
Thu Jul 31 19:44:49 CEST 2008

On 7/29/08, Chris Rebert <cvrebert at gmail.com> wrote:
>  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.

Not quite.

>  So really it comes down to answering the question: "Can mutating an
>  instance of my class affect its equality with other instances?"

Sort of.

The only time hash ever gets used is when your object is the key of a
dict (or set, or similar).  If changes can affect equality, then it
*usually* isn't suitable for use as a key, and there is no point to
making a hash.

But if the mutability is limited, it might still be OK.

Things that are equal must hash equal, but things that are unequal can
hash however they want.  (hashing unequal is useful for efficiency,
but not required.)

For example, if your objects used two attributes for equality, but
only one of them was immutable, it would be OK to use (only) the
immutable attribute for the hash; things that were even potentially
equal would hash together, which is the only strict requirement.
(Debugging would be a pain though, because whether keys were
equivalent could change between the time the dict checked and the time
you were investigating.)


More information about the Python-3000 mailing list