[Python-checkins] gh-91081: Add note on WeakKeyDictionary behavior when deleting a replaced entry (#91499)

JelleZijlstra webhook-mailer at python.org
Tue Dec 20 22:27:07 EST 2022


https://github.com/python/cpython/commit/c615286e8576f2555d4380f38a966c300805b1a5
commit: c615286e8576f2555d4380f38a966c300805b1a5
branch: main
author: Stanley <46876382+slateny at users.noreply.github.com>
committer: JelleZijlstra <jelle.zijlstra at gmail.com>
date: 2022-12-20T19:27:02-08:00
summary:

gh-91081: Add note on WeakKeyDictionary behavior when deleting a replaced entry (#91499)

Co-authored-by: Pieter Eendebak <P.T.eendebak at tudelft.nl>
Co-authored-by: Jelle Zijlstra <jelle.zijlstra at gmail.com>

files:
M Doc/library/weakref.rst

diff --git a/Doc/library/weakref.rst b/Doc/library/weakref.rst
index 73e7b21ae405..1406b663c6a8 100644
--- a/Doc/library/weakref.rst
+++ b/Doc/library/weakref.rst
@@ -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`.
 



More information about the Python-checkins mailing list