Skip to content

Commit

Permalink
Improve documentation of safety constraints on hashable objects (#505)
Browse files Browse the repository at this point in the history
* Clarify documentation for hashing

Makes clear that hashable objects need to be deeply immutable, in
practice even if not in theory.

Closes #503 .

* Use simple past tense in docs
  • Loading branch information
Ryan Gabbard authored and hynek committed Feb 14, 2019
1 parent 7b37354 commit 659aa48
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 5 deletions.
1 change: 1 addition & 0 deletions changelog.d/503.change.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Clarified documentation for hashing to warn that hashable objects should be deeply immutable (in their usage, even if this is not enforced).
4 changes: 3 additions & 1 deletion docs/hashing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,9 @@ For a more thorough explanation of this topic, please refer to this blog post: `
Hashing and Mutability
----------------------
Changing any field involved in hash code computation after the first call to `__hash__` (typically this would be after its insertion into a hash-based collection) can result in silent bugs.
Therefore, it is strongly recommended that hashable classes be ``frozen``.
Therefore, it is strongly recommended that hashable classes be ``frozen.``
Beware, however, that this is not a complete guarantee of safety:
if a field points to an object and that object is mutated, the hash code may change, but ``frozen`` will not protect you.


Hash Code Caching
Expand Down
8 changes: 4 additions & 4 deletions src/attr/_make.py
Original file line number Diff line number Diff line change
Expand Up @@ -843,10 +843,10 @@ def attrs(
:param bool cache_hash: Ensure that the object's hash code is computed
only once and stored on the object. If this is set to ``True``,
hashing must be either explicitly or implicitly enabled for this
class. If the hash code is cached, then no attributes of this
class which participate in hash code computation may be mutated
after object creation.
class. If the hash code is cached, avoid any reassignments of
fields involved in hash code computation or mutations of the objects
those fields point to after object creation. If such changes occur,
the behavior of the object's hash code is undefined.
.. versionadded:: 16.0.0 *slots*
.. versionadded:: 16.1.0 *frozen*
Expand Down

0 comments on commit 659aa48

Please sign in to comment.