Skip to content

Commit

Permalink
gh-91081: Add note on WeakKeyDictionary behavior when deleting a repl…
Browse files Browse the repository at this point in the history
…aced entry (GH-91499)

(cherry picked from commit c615286)

Co-authored-by: Stanley <46876382+slateny@users.noreply.github.com>
Co-authored-by: Pieter Eendebak <P.T.eendebak@tudelft.nl>
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
  • Loading branch information
4 people authored Dec 21, 2022
1 parent 23fa166 commit fe828ec
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions Doc/library/weakref.rst
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,30 @@ See :ref:`__slots__ documentation <slots>` for details.
application without adding attributes to those objects. This can be especially
useful with objects that override attribute accesses.

Note that when a key with equal value to an existing key (but not equal identity)
is inserted into the dictionary, it replaces the value but does not replace the
existing key. Due to this, when the reference to the original key is deleted, it
also deletes the entry in the dictionary::

>>> class T(str): pass
...
>>> k1, k2 = T(), T()
>>> d = weakref.WeakKeyDictionary()
>>> d[k1] = 1 # d = {k1: 1}
>>> d[k2] = 2 # d = {k1: 2}
>>> del k1 # d = {}

A workaround would be to remove the key prior to reassignment::

>>> class T(str): pass
...
>>> k1, k2 = T(), T()
>>> d = weakref.WeakKeyDictionary()
>>> d[k1] = 1 # d = {k1: 1}
>>> del d[k1]
>>> d[k2] = 2 # d = {k2: 2}
>>> del k1 # d = {k2: 2}

.. versionchanged:: 3.9
Added support for ``|`` and ``|=`` operators, specified in :pep:`584`.

Expand Down

0 comments on commit fe828ec

Please sign in to comment.