Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 73c96db

Browse files
committed
Merged revisions 66085 (with modifications) via svnmerge from
svn+ssh://[email protected]/python/trunk ........ r66085 | nick.coghlan | 2008-08-31 23:10:50 +1000 (Sun, 31 Aug 2008) | 1 line Issue 2235: document the ability to block inheritance of __hash__ in the language reference ........
1 parent 3a5d7e3 commit 73c96db

1 file changed

Lines changed: 21 additions & 4 deletions

File tree

Doc/reference/datamodel.rst

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1239,12 +1239,29 @@ Basic customization
12391239
be in the wrong hash bucket).
12401240

12411241
User-defined classes have :meth:`__cmp__` and :meth:`__hash__` methods
1242-
by default; with them, all objects compare unequal and ``x.__hash__()``
1243-
returns ``id(x)``.
1244-
1242+
by default; with them, all objects compare unequal (except with themselves)
1243+
and ``x.__hash__()`` returns ``id(x)``.
1244+
1245+
Classes which inherit a :meth:`__hash__` method from a parent class but
1246+
change the meaning of :meth:`__cmp__` or :meth:`__eq__` such that the hash
1247+
value returned is no longer appropriate (e.g. by switching to a value-based
1248+
concept of equality instead of the default identity based equality) can
1249+
explicitly flag themselves as being unhashable by setting
1250+
``__hash__ = None`` in the class definition. Doing so means that not only
1251+
will instances of the class raise an appropriate :exc:`TypeError` when
1252+
a program attempts to retrieve their hash value, but they will also be
1253+
correctly identified as unhashable when checking
1254+
``isinstance(obj, collections.Hashable)`` (unlike classes which define
1255+
their own :meth:`__hash__` to explicitly raise :exc:`TypeError`).
1256+
1257+
If a class that overrrides :meth:`__cmp__` or :meth:`__eq__` needs to
1258+
retain the implementation of :meth:`__hash__` from a parent class,
1259+
the interpreter must be told this explicitly by setting
1260+
``__hash__ = <ParentClass>.__hash__``. Otherwise the inheritance of
1261+
:meth:`__hash__` will be blocked, just as if :attr:`__hash__` had been
1262+
explicitly set to :const:`None`.
12451263

12461264
.. method:: object.__bool__(self)
1247-
12481265
.. index:: single: __len__() (mapping object method)
12491266

12501267
Called to implement truth value testing, and the built-in operation ``bool()``;

0 commit comments

Comments
 (0)