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

Skip to content

Commit 509476b

Browse files
committed
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.
1 parent bfbc29c commit 509476b

1 file changed

Lines changed: 8 additions & 5 deletions

File tree

Doc/reference/datamodel.rst

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1305,11 +1305,14 @@ Basic customization
13051305

13061306
Called by built-in function :func:`hash` and for operations on members of
13071307
hashed collections including :class:`set`, :class:`frozenset`, and
1308-
:class:`dict`. :meth:`__hash__` should return an integer. The only
1309-
required property is that objects which compare equal have the same hash
1310-
value; it is advised to somehow mix together (e.g. using exclusive or) the
1311-
hash values for the components of the object that also play a part in
1312-
comparison of objects.
1308+
:class:`dict`. :meth:`__hash__` should return an integer. The only required
1309+
property is that objects which compare equal have the same hash value; it is
1310+
advised to mix together the hash values of the components of the object that
1311+
also play a part in comparison of objects by packing them into a tuple and
1312+
hashing the tuple. Example::
1313+
1314+
def __hash__(self):
1315+
return hash((self.name, self.nick, self.color))
13131316

13141317
.. note::
13151318

0 commit comments

Comments
 (0)