Skip to content

Update docs: mention setting __hash__ = None for custom __eq__ method #2287

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/advanced/classes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -695,6 +695,13 @@ throwing a type error.

To use the more convenient ``py::self`` notation, the additional
header file :file:`pybind11/operators.h` must be included.

.. note::

A class that overrides ``__eq__()`` and does not define ``__hash__()`` will have its ``__hash__()`` implicitly set.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: When a class overrides __eq__() and does not define __hash__(), pybind11 will automatically add a __hash__(). (I think this rewording makes it more clear that this behavior is something pybind11 does.)

This is a deviation from the standard Python behaviour where ``__hash__()`` is set to ``None`` when overriding ``__eq__()``. To restore the default behaviour
one can use ``.attr("__hash__") = py::none()``. When set ``None`` the class will raise an appropriate TypeError when a program attempts to retrieve their
hash value, and will also be correctly identified as unhashable when checking ``isinstance(obj, collections.abc.Hashable)``.

.. seealso::

Expand Down