https://github.com/python/cpython/commit/50b45c4f457a7b77ec526fae4d2894c3e4f38e2e
commit: 50b45c4f457a7b77ec526fae4d2894c3e4f38e2e
branch: 3.13
author: Brandt Bucher <brandtbuc...@microsoft.com>
committer: brandtbucher <brandtbuc...@gmail.com>
date: 2025-05-12T13:00:01-07:00
summary:

[3.13] GH-133543: Maintain tracking for materialized instance dictionaries 
(GH-133617)

files:
A 
Misc/NEWS.d/next/Core_and_Builtins/2025-05-07-10-48-31.gh-issue-133543.4jcszP.rst
M Lib/test/test_dict.py
M Objects/dictobject.c

diff --git a/Lib/test/test_dict.py b/Lib/test/test_dict.py
index 40b0c210ab34b0..4729132c5a5f84 100644
--- a/Lib/test/test_dict.py
+++ b/Lib/test/test_dict.py
@@ -1006,6 +1006,18 @@ class MyDict(dict):
             pass
         self._tracked(MyDict())
 
+    @support.cpython_only
+    def test_track_lazy_instance_dicts(self):
+        class C:
+            pass
+        o = C()
+        d = o.__dict__
+        self._not_tracked(d)
+        o.untracked = 42
+        self._not_tracked(d)
+        o.tracked = []
+        self._tracked(d)
+
     def make_shared_key_dict(self, n):
         class C:
             pass
diff --git 
a/Misc/NEWS.d/next/Core_and_Builtins/2025-05-07-10-48-31.gh-issue-133543.4jcszP.rst
 
b/Misc/NEWS.d/next/Core_and_Builtins/2025-05-07-10-48-31.gh-issue-133543.4jcszP.rst
new file mode 100644
index 00000000000000..046085892d45e6
--- /dev/null
+++ 
b/Misc/NEWS.d/next/Core_and_Builtins/2025-05-07-10-48-31.gh-issue-133543.4jcszP.rst
@@ -0,0 +1,2 @@
+Fix a possible memory leak that could occur when directly accessing instance
+dictionaries (``__dict__``) that later become part of a reference cycle.
diff --git a/Objects/dictobject.c b/Objects/dictobject.c
index e89ed467bf7c27..501f3d2d2bcaf5 100644
--- a/Objects/dictobject.c
+++ b/Objects/dictobject.c
@@ -6839,6 +6839,9 @@ store_instance_attr_lock_held(PyObject *obj, PyDictValues 
*values,
                                    value == NULL ? PyDict_EVENT_DELETED :
                                    PyDict_EVENT_MODIFIED);
         _PyDict_NotifyEvent(interp, event, dict, name, value);
+        if (value) {
+            MAINTAIN_TRACKING(dict, name, value);
+        }
     }
 
     FT_ATOMIC_STORE_PTR_RELEASE(values->values[ix], Py_XNewRef(value));

_______________________________________________
Python-checkins mailing list -- python-checkins@python.org
To unsubscribe send an email to python-checkins-le...@python.org
https://mail.python.org/mailman3/lists/python-checkins.python.org/
Member address: arch...@mail-archive.com

Reply via email to