Skip to content

Commit

Permalink
Add workaround example
Browse files Browse the repository at this point in the history
  • Loading branch information
slateny committed Dec 10, 2022
1 parent 69b3231 commit 9f22bd7
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions Doc/library/weakref.rst
Original file line number Diff line number Diff line change
Expand Up @@ -172,15 +172,25 @@ See :ref:`__slots__ documentation <slots>` for details.
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
>>> 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}
>>> d.pop(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 9f22bd7

Please sign in to comment.