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

Skip to content

Commit a96be78

Browse files
committed
Merge #14617: clarify discussion of interrelationship of __eq__ and __hash__.
2 parents 7872697 + d8bbde3 commit a96be78

1 file changed

Lines changed: 13 additions & 13 deletions

File tree

Doc/reference/datamodel.rst

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1271,22 +1271,22 @@ Basic customization
12711271
and ``x.__hash__()`` returns an appropriate value such that ``x == y``
12721272
implies both that ``x is y`` and ``hash(x) == hash(y)``.
12731273

1274-
Classes which inherit a :meth:`__hash__` method from a parent class but
1275-
change the meaning of :meth:`__eq__` such that the hash value returned is no
1276-
longer appropriate (e.g. by switching to a value-based concept of equality
1277-
instead of the default identity based equality) can explicitly flag
1278-
themselves as being unhashable by setting ``__hash__ = None`` in the class
1279-
definition. Doing so means that not only will instances of the class raise an
1280-
appropriate :exc:`TypeError` when a program attempts to retrieve their hash
1281-
value, but they will also be correctly identified as unhashable when checking
1282-
``isinstance(obj, collections.Hashable)`` (unlike classes which define their
1283-
own :meth:`__hash__` to explicitly raise :exc:`TypeError`).
1274+
A class that overrides :meth:`__eq__` and does not define :meth:`__hash__`
1275+
will have its :meth:`__hash__` implicitly set to ``None``. When the
1276+
:meth:`__hash__` method of a class is ``None``, instances of the class will
1277+
raise an appropriate :exc:`TypeError` when a program attempts to retrieve
1278+
their hash value, and will also be correctly identified as unhashable when
1279+
checking ``isinstance(obj, collections.Hashable``).
12841280

12851281
If a class that overrides :meth:`__eq__` needs to retain the implementation
12861282
of :meth:`__hash__` from a parent class, the interpreter must be told this
1287-
explicitly by setting ``__hash__ = <ParentClass>.__hash__``. Otherwise the
1288-
inheritance of :meth:`__hash__` will be blocked, just as if :attr:`__hash__`
1289-
had been explicitly set to :const:`None`.
1283+
explicitly by setting ``__hash__ = <ParentClass>.__hash__``.
1284+
1285+
If a class that does not override :meth:`__eq__` wishes to suppress hash
1286+
support, it should include ``__hash__ = None`` in the class definition.
1287+
A class which defines its own :meth:`__hash__` that explicitly raises
1288+
a :exc:`TypeError` would be incorrectly identified as hashable by
1289+
an ``isinstance(obj, collections.Hashable)`` call.
12901290

12911291

12921292
.. note::

0 commit comments

Comments
 (0)