Skip to content

Commit fe828ec

Browse files
miss-islingtonslatenypeendebakJelleZijlstra
authored
gh-91081: Add note on WeakKeyDictionary behavior when deleting a replaced entry (GH-91499)
(cherry picked from commit c615286) Co-authored-by: Stanley <[email protected]> Co-authored-by: Pieter Eendebak <[email protected]> Co-authored-by: Jelle Zijlstra <[email protected]>
1 parent 23fa166 commit fe828ec

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

Doc/library/weakref.rst

+24
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,30 @@ See :ref:`__slots__ documentation <slots>` for details.
172172
application without adding attributes to those objects. This can be especially
173173
useful with objects that override attribute accesses.
174174

175+
Note that when a key with equal value to an existing key (but not equal identity)
176+
is inserted into the dictionary, it replaces the value but does not replace the
177+
existing key. Due to this, when the reference to the original key is deleted, it
178+
also deletes the entry in the dictionary::
179+
180+
>>> class T(str): pass
181+
...
182+
>>> k1, k2 = T(), T()
183+
>>> d = weakref.WeakKeyDictionary()
184+
>>> d[k1] = 1 # d = {k1: 1}
185+
>>> d[k2] = 2 # d = {k1: 2}
186+
>>> del k1 # d = {}
187+
188+
A workaround would be to remove the key prior to reassignment::
189+
190+
>>> class T(str): pass
191+
...
192+
>>> k1, k2 = T(), T()
193+
>>> d = weakref.WeakKeyDictionary()
194+
>>> d[k1] = 1 # d = {k1: 1}
195+
>>> del d[k1]
196+
>>> d[k2] = 2 # d = {k2: 2}
197+
>>> del k1 # d = {k2: 2}
198+
175199
.. versionchanged:: 3.9
176200
Added support for ``|`` and ``|=`` operators, specified in :pep:`584`.
177201

0 commit comments

Comments
 (0)