Skip to content

Commit c6924e9

Browse files
slatenypeendebakJelleZijlstra
authored andcommitted
pythongh-91081: Add note on WeakKeyDictionary behavior when deleting a replaced entry (pythonGH-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>
1 parent b3d39c7 commit c6924e9

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
@@ -170,6 +170,30 @@ See :ref:`__slots__ documentation <slots>` for details.
170170
application without adding attributes to those objects. This can be especially
171171
useful with objects that override attribute accesses.
172172

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

0 commit comments

Comments
 (0)