From c6924e99c9e5051778d7c7dd6c2d71d3149fc9b7 Mon Sep 17 00:00:00 2001
From: Stanley <46876382+slateny@users.noreply.github.com>
Date: Tue, 20 Dec 2022 19:27:02 -0800
Subject: [PATCH] gh-91081: Add note on WeakKeyDictionary behavior when
deleting a replaced entry (GH-91499) (cherry picked from commit
c615286e8576f2555d4380f38a966c300805b1a5)
Co-authored-by: Stanley <46876382+slateny@users.noreply.github.com>
Co-authored-by: Pieter Eendebak
Co-authored-by: Jelle Zijlstra
---
Doc/library/weakref.rst | 24 ++++++++++++++++++++++++
1 file changed, 24 insertions(+)
diff --git a/Doc/library/weakref.rst b/Doc/library/weakref.rst
index 9a8289a7b533a7..ffe94be8087d02 100644
--- a/Doc/library/weakref.rst
+++ b/Doc/library/weakref.rst
@@ -170,6 +170,30 @@ See :ref:`__slots__ documentation ` 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`.
pFad - Phonifier reborn
Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies:
Alternative Proxy
pFad Proxy
pFad v3 Proxy
pFad v4 Proxy