[Python-checkins] cpython (3.5): doc: Suggest to hash(tuple of attr) rather than XOR

victor.stinner python-checkins at python.org
Mon Dec 19 07:10:41 EST 2016


https://hg.python.org/cpython/rev/cb802a78ceea
changeset:   105745:cb802a78ceea
branch:      3.5
parent:      105742:8f5ed2a38f64
user:        Victor Stinner <victor.stinner at gmail.com>
date:        Mon Dec 19 13:09:28 2016 +0100
summary:
  doc: Suggest to hash(tuple of attr) rather than XOR

Issue #28383: __hash__ documentation recommends naive XOR to combine but this
is suboptimal. Update the doc to suggest to reuse the hash() method using a
tuple, with an example.

files:
  Doc/reference/datamodel.rst |  13 ++++++++-----
  1 files changed, 8 insertions(+), 5 deletions(-)


diff --git a/Doc/reference/datamodel.rst b/Doc/reference/datamodel.rst
--- a/Doc/reference/datamodel.rst
+++ b/Doc/reference/datamodel.rst
@@ -1305,11 +1305,14 @@
 
    Called by built-in function :func:`hash` and for operations on members of
    hashed collections including :class:`set`, :class:`frozenset`, and
-   :class:`dict`.  :meth:`__hash__` should return an integer.  The only
-   required property is that objects which compare equal have the same hash
-   value; it is advised to somehow mix together (e.g. using exclusive or) the
-   hash values for the components of the object that also play a part in
-   comparison of objects.
+   :class:`dict`.  :meth:`__hash__` should return an integer. The only required
+   property is that objects which compare equal have the same hash value; it is
+   advised to mix together the hash values of the components of the object that
+   also play a part in comparison of objects by packing them into a tuple and
+   hashing the tuple. Example::
+
+       def __hash__(self):
+           return hash((self.name, self.nick, self.color))
 
    .. note::
 

-- 
Repository URL: https://hg.python.org/cpython


More information about the Python-checkins mailing list