Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions Lib/test/test_opcache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Preserve built-in data descriptor precedence when specializing attribute loads
on module objects, including dictionary entries shadowing ``__dict__`` and
``__class__``.
8 changes: 8 additions & 0 deletions Python/specialize.c
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading