Skip to content

Commit 08f8818

Browse files
committed
Look into module dict for its name
1 parent a7e7f0a commit 08f8818

2 files changed

Lines changed: 11 additions & 6 deletions

File tree

Lib/test/test_exceptions.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2153,7 +2153,8 @@ def raise_custom(name):
21532153
self.assertIs(cm.exception.obj, custom_mod)
21542154
self.assertEqual(cm.exception.name, "missing3")
21552155

2156-
nameless_mod = ModuleType.__new__(ModuleType)
2156+
nameless_mod = ModuleType("forgettable")
2157+
del nameless_mod.__dict__["__name__"]
21572158
nameless_mod.__getattr__ = raise_with_name
21582159
with self.assertRaises(AttributeError) as cm:
21592160
getattr(nameless_mod, "missing4")

Objects/exceptions.c

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2727,14 +2727,17 @@ AttributeError_str(PyObject *op)
27272727
return BaseException_str(op); /* re-acquires lock */
27282728
}
27292729

2730-
PyObject *result;
2730+
PyObject *result = NULL;
27312731
if (PyModule_Check(obj)) {
27322732
PyModuleObject *mod = _PyModule_CAST(obj);
2733-
/* In a typical case, module's __name__ is examined instead. */
2734-
if (mod->md_name) {
2733+
PyObject *modname;
2734+
if (PyDict_GetItemRef(mod->md_dict, &_Py_ID(__name__), &modname) < 0) {
2735+
goto error;
2736+
}
2737+
if (modname) {
27352738
result = PyUnicode_FromFormat("module '%U' has no attribute '%U'",
2736-
mod->md_name,
2737-
name);
2739+
modname, name);
2740+
Py_DECREF(modname);
27382741
} else {
27392742
result = PyUnicode_FromFormat("module has no attribute '%U'", name);
27402743
}
@@ -2745,6 +2748,7 @@ AttributeError_str(PyObject *op)
27452748
result = PyUnicode_FromFormat("'%T' object has no attribute '%U'",
27462749
obj, name);
27472750
}
2751+
error:
27482752
Py_DECREF(obj);
27492753
Py_DECREF(name);
27502754
return result;

0 commit comments

Comments
 (0)