summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorVictor Stinner <victor.stinner@gmail.com>2016-12-19 12:15:35 (GMT)
committerVictor Stinner <victor.stinner@gmail.com>2016-12-19 12:15:35 (GMT)
commitf6447e006587fcb632b80ca7e5888cefc1a26d58 (patch)
treeaee08bc2d5f095e9c3c9295d13c0f6b87ebe836b
parent805f283aa311043a498fecc29cf7bc13e4311fd6 (diff)
downloadcpython-f6447e006587fcb632b80ca7e5888cefc1a26d58.zip
cpython-f6447e006587fcb632b80ca7e5888cefc1a26d58.tar.gz
cpython-f6447e006587fcb632b80ca7e5888cefc1a26d58.tar.bz2
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.
-rw-r--r--Doc/reference/datamodel.rst8
1 files changed, 6 insertions, 2 deletions
diff --git a/Doc/reference/datamodel.rst b/Doc/reference/datamodel.rst
index db2fa17..4adf5fa 100644
--- a/Doc/reference/datamodel.rst
+++ b/Doc/reference/datamodel.rst
@@ -1409,8 +1409,12 @@ Basic customization
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.
+ 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))
If a class does not define a :meth:`__cmp__` or :meth:`__eq__` method it
should not define a :meth:`__hash__` operation either; if it defines