[Python-Dev] object.__hash__() vs. hash()

Raymond Hettinger raymond.hettinger at verizon.net
Wed Sep 3 16:55:46 EDT 2003


object.__hash__() returns id(obj) by default.

__builtin__.hash() uses PyObject_Hash() which is a bit smarter
and avoids id(obj) whenever a comparison function is defined.

Does anyone see a problem with my adding a similiar guard
to object.__hash__()?

This will prevent recurrence of a bug for newstyle objects which
define a comparison function but not a hash function.  For instance,
slice(5).__hash__() is defined, but hash(slice(5)) raises a TypeError.

An alternative solution is to change the logic in the slot 
inheritance to not inherit tp_hash whenever tp_compare or
tp_richcompare is defined.   This approach is a bit more tangled
and may have unforeseen consequences, but has the advantage
of preventing __hash__ from showing up method list for
the subclass:  dir(slice(5)) currently contains '__hash__'.

I prefer the first approach of making object.__hash__() smarter.


Raymond Hettinger






More information about the Python-Dev mailing list