[docs] [issue15981] improve documentation of __hash__

Max report at bugs.python.org
Thu Sep 20 13:00:24 CEST 2012


New submission from Max:

In dev/reference/datamodel#object.__hash__, there are two paragraphs that seem inconsistent. The first paragraph seems to say that a class that overrides __eq__() *should* explicitly flag itself as unhashable. The next paragraph says that a class that overrides __eq__() *will be* flagged unhashable by default. Which one is it?

Here are the two paragraphs:

Classes which inherit a __hash__() method from a parent class but change the meaning of __eq__() such that the hash value returned is no longer appropriate (e.g. by switching to a value-based concept of equality instead of the default identity based equality) can explicitly flag themselves as being unhashable by setting __hash__ = None in the class definition. Doing so means that not only will instances of the class raise an appropriate TypeError when a program attempts to retrieve their hash value, but they will also be correctly identified as unhashable when checking isinstance(obj, collections.Hashable) (unlike classes which define their own __hash__() to explicitly raise TypeError).

If a class that overrides __eq__() needs to retain the implementation of __hash__() from a parent class, the interpreter must be told this explicitly by setting __hash__ = <ParentClass>.__hash__. Otherwise the inheritance of __hash__() will be blocked, just as if __hash__ had been explicitly set to None.

----------
assignee: docs at python
components: Documentation
messages: 170798
nosy: docs at python, max
priority: normal
severity: normal
status: open
title: improve documentation of __hash__
type: enhancement
versions: Python 3.3

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue15981>
_______________________________________


More information about the docs mailing list