gh-91081: Add note on WeakKeyDictionary behavior when deleting a repl… · miss-islington/cpython@c6924e9

GitHub

GitHub CopilotWrite better code with AI | MCP RegistryIntegrate external tools | ActionsAutomate any workflow | CodespacesInstant dev environments | IssuesPlan and track work | Code ReviewManage code changes | Code QualityEnforce quality at merge | Why GitHub | Marketplace | View all features | Enterprises | Small and medium teams | Startups | View all use cases | View all industries | View all solutions | AI | Software Development | DevOps | Security | View all topics | Customer stories | Events & webinars | Ebooks & reports | Business insights | Trust center | Partners | View all resources

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.

172172173+ 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