diff options
author | Victor Stinner <victor.stinner@gmail.com> | 2016-12-19 12:09:28 (GMT) |
---|---|---|
committer | Victor Stinner <victor.stinner@gmail.com> | 2016-12-19 12:09:28 (GMT) |
commit | 509476b37085abda9c8cc0fba1451cb035e0b442 (patch) | |
tree | d284534019144fcfa4f4fa52fc32f307c1fb21c0 /Doc/reference | |
parent | bfbc29cb8f5797f239a6ad8944edfea4e153cb75 (diff) | |
download | cpython-509476b37085abda9c8cc0fba1451cb035e0b442.zip cpython-509476b37085abda9c8cc0fba1451cb035e0b442.tar.gz cpython-509476b37085abda9c8cc0fba1451cb035e0b442.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.
Diffstat (limited to 'Doc/reference')
-rw-r--r-- | Doc/reference/datamodel.rst | 13 |
1 files changed, 8 insertions, 5 deletions
diff --git a/Doc/reference/datamodel.rst b/Doc/reference/datamodel.rst index b763f10..73eec1c 100644 --- a/Doc/reference/datamodel.rst +++ b/Doc/reference/datamodel.rst @@ -1305,11 +1305,14 @@ Basic customization 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:: |