GH-92678: Expose managed dict clear and visit functions (#95246) · python/cpython@27055d7 · GitHub
Skip to content

Commit 27055d7

Browse files
authored
GH-92678: Expose managed dict clear and visit functions (#95246)
1 parent 2d26449 commit 27055d7

5 files changed

Lines changed: 57 additions & 0 deletions

File tree

Include/cpython/dictobject.h

Lines changed: 3 additions & 0 deletions

Lib/test/test_capi.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -722,6 +722,20 @@ def test_export_symbols(self):
722722
with self.subTest(name=name):
723723
self.assertTrue(hasattr(ctypes.pythonapi, name))
724724

725+
def test_clear_managed_dict(self):
726+
727+
class C:
728+
def __init__(self):
729+
self.a = 1
730+
731+
c = C()
732+
_testcapi.clear_managed_dict(c)
733+
self.assertEqual(c.__dict__, {})
734+
c = C()
735+
self.assertEqual(c.__dict__, {'a':1})
736+
_testcapi.clear_managed_dict(c)
737+
self.assertEqual(c.__dict__, {})
738+
725739

726740
class TestPendingCalls(unittest.TestCase):
727741

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Adds unstable C-API functions ``_PyObject_VisitManagedDict`` and
2+
``_PyObject_ClearManagedDict`` to allow C extensions to allow the VM to
3+
manage their object's dictionaries.

Modules/_testcapimodule.c

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6009,6 +6009,13 @@ settrace_to_record(PyObject *self, PyObject *list)
60096009
Py_RETURN_NONE;
60106010
}
60116011

6012+
static PyObject *
6013+
clear_managed_dict(PyObject *self, PyObject *obj)
6014+
{
6015+
_PyObject_ClearManagedDict(obj);
6016+
Py_RETURN_NONE;
6017+
}
6018+
60126019

60136020
static PyObject *
60146021
test_macros(PyObject *self, PyObject *Py_UNUSED(args))
@@ -6347,6 +6354,7 @@ static PyMethodDef TestMethods[] = {
63476354
{"test_code_api", test_code_api, METH_NOARGS, NULL},
63486355
{"settrace_to_record", settrace_to_record, METH_O, NULL},
63496356
{"test_macros", test_macros, METH_NOARGS, NULL},
6357+
{"clear_managed_dict", clear_managed_dict, METH_O, NULL},
63506358
{NULL, NULL} /* sentinel */
63516359
};
63526360

Objects/dictobject.c

Lines changed: 29 additions & 0 deletions

0 commit comments

Comments
 (0)