Skip to content

Commit 9f22bd7

Browse files
committed
Add workaround example
1 parent 69b3231 commit 9f22bd7

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

Doc/library/weakref.rst

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -172,15 +172,25 @@ See :ref:`__slots__ documentation <slots>` for details.
172172
existing key. Due to this, when the reference to the original key is deleted, it
173173
also deletes the entry in the dictionary::
174174

175-
>>> class T(str):
176-
... pass
175+
>>> class T(str): pass
177176
...
178177
>>> k1, k2 = T(), T()
179178
>>> d = weakref.WeakKeyDictionary()
180179
>>> d[k1] = 1 # d = {k1: 1}
181180
>>> d[k2] = 2 # d = {k1: 2}
182181
>>> del k1 # d = {}
183182

183+
A workaround would be to remove the key prior to reassignment::
184+
185+
>>> class T(str): pass
186+
...
187+
>>> k1, k2 = T(), T()
188+
>>> d = weakref.WeakKeyDictionary()
189+
>>> d[k1] = 1 # d = {k1: 1}
190+
>>> d.pop(k1)
191+
>>> d[k2] = 2 # d = {k2: 2}
192+
>>> del k1 # d = {k2: 2}
193+
184194
.. versionchanged:: 3.9
185195
Added support for ``|`` and ``|=`` operators, specified in :pep:`584`.
186196

0 commit comments

Comments
 (0)