[Python-Dev] getting rid of default object.__hash__ (SF 660098)

Guido van Rossum guido at python.org
Mon Dec 22 16:04:11 EST 2003

New-style classes inherit a default __hash__ from object, but this
is incorrect if the inheriting object defines __eq__ or __cmp__.

This has been reported several times; the roll-up SF entry is 660098,
which has the proposed patch attached as newpatch.txt.

I've long pondered this, and it seems the best solution is to simply
not define __hash__ on the base object class.  After all, you don't
inherit __eq__ or __cmp__ either; the default comparison behavior is
supplied by intrinsic behavior of comparisons, and the default hash()
behavior is also supplied by intrinsic behavior of hash().

Does anybody have any reason why I shouldn't check in this change in
2.4?  There's no unit test that fails if I do this.

It *is* a slight incompatibility though: if someone implemented their
__hash__ in terms of object.__hash__, they would get a somewhat
puzzling error message after the change, because object.__hash__ will
refer to the type.__hash__ function bound to object, and refuse to
take an argument:

  >>> object.__hash__()
  >>> object.__hash__(42)
  Traceback (most recent call last):
    File "<stdin>", line 1, in ?
  TypeError:  expected 0 arguments, got 1

Since the default hash simply takes id() of the object, it's easy to
fix such code once the failure is understood though.

--Guido van Rossum (home page: http://www.python.org/~guido/)

More information about the Python-Dev mailing list