new-style classes, __hash__. is the documentation wrong?

Klaas mike.klaas at gmail.com
Wed Oct 25 15:28:12 EDT 2006


gabor wrote:

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

> now, with new style classes, the class will have __hash__, whatever i
> do. (well, i assume i could play with __getattribute__...).

There is a proposal to fix this, though I don't think we'll see it for
a while.

class CantHash(object):
    __hash__ = None

> so is that part of the documentation currently wrong?

yes

> because from what i see (the bug will not be fixed),
> it's still much safer to define a __hash__ even for mutable objects
> (when the object also defines __eq__).

Better is to define __hash__ in a way that prevents errors:

class Mutable(object):
    def __hash__(self):
          raise TypeError('unhashable instance')

It will behave similarly to an old-style class that defines __eq__ and
not __hash__

-Mike




More information about the Python-list mailing list