From 58ec70142df81080db227bf135b42cc07e7e1816 Mon Sep 17 00:00:00 2001 From: lagergren-oai Date: Tue, 24 Nov 2026 17:38:35 +0100 Subject: [PATCH] gh-162565: Preserve module data descriptor precedence during specialization --- Lib/test/test_opcache.py | 24 +++++++++++++++++++ ...-11-24-17-40-00.gh-issue-162565.kA7vQ2.rst | 3 +++ Python/specialize.c | 8 +++++++ 3 files changed, 35 insertions(+) create mode 100644 Misc/NEWS.d/next/Core_and_Builtins/2026-11-24-17-40-00.gh-issue-162565.kA7vQ2.rst diff --git a/Lib/test/test_opcache.py b/Lib/test/test_opcache.py index 5f7c15f93a8332..340e5600957424 100644 --- a/Lib/test/test_opcache.py +++ b/Lib/test/test_opcache.py @@ -2326,6 +2326,30 @@ def load_module_attr_missing(): finally: sys.modules.pop("test_module_with_getattr", None) + @cpython_only + @requires_specialization + def test_load_attr_module_builtin_data_descriptors(self): + def load_dict(module): + return module.__dict__ + + def load_class(module): + return module.__class__ + + for name, load_attr in ( + ("__dict__", load_dict), + ("__class__", load_class), + ): + with self.subTest(name=name): + module = types.ModuleType("test_module_builtin_descriptor") + namespace = vars(module) + namespace[name] = object() + expected = namespace if name == "__dict__" else types.ModuleType + + for _ in range(_testinternalcapi.SPECIALIZATION_THRESHOLD): + self.assertIs(load_attr(module), expected) + + self.assert_no_opcode(load_attr, "LOAD_ATTR_MODULE") + @cpython_only @requires_specialization def test_load_attr_module_subclass_with_data_descriptor(self): diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-24-17-40-00.gh-issue-162565.kA7vQ2.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-24-17-40-00.gh-issue-162565.kA7vQ2.rst new file mode 100644 index 00000000000000..08fd6a06d31be4 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-24-17-40-00.gh-issue-162565.kA7vQ2.rst @@ -0,0 +1,3 @@ +Preserve built-in data descriptor precedence when specializing attribute loads +on module objects, including dictionary entries shadowing ``__dict__`` and +``__class__``. diff --git a/Python/specialize.c b/Python/specialize.c index b5cf4ebc31142a..11e03791dcb082 100644 --- a/Python/specialize.c +++ b/Python/specialize.c @@ -457,6 +457,14 @@ specialize_module_load_attr( SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_NO_DICT); return -1; } + // Module data descriptors take precedence over the module dictionary. + PyObject *descriptor = _PyType_LookupRef(&PyModule_Type, name); + bool overrides_dict = descriptor != NULL && PyDescr_IsData(descriptor); + Py_XDECREF(descriptor); + if (overrides_dict) { + SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_ATTR_OVERRIDING_DESCRIPTOR); + return -1; + } int result; Py_BEGIN_CRITICAL_SECTION(dict); result = specialize_module_load_attr_lock_held(dict, instr, name);