Skip to content

Commit 6db7033

Browse files
orenmnserhiy-storchaka
authored andcommitted
bpo-31492: Fix assertion failures in case of a module with a bad __name__ attribute. (#3620)
1 parent 453408a commit 6db7033

File tree

4 files changed

+20
-4
lines changed

4 files changed

+20
-4
lines changed

Lib/test/test_import/__init__.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -400,6 +400,18 @@ def __getattr__(self, _):
400400
self.assertEqual(str(cm.exception),
401401
"cannot import name 'does_not_exist' from '<unknown module name>' (unknown location)")
402402

403+
@cpython_only
404+
def test_issue31492(self):
405+
# There shouldn't be an assertion failure in case of failing to import
406+
# from a module with a bad __name__ attribute, or in case of failing
407+
# to access an attribute of such a module.
408+
with swap_attr(os, '__name__', None):
409+
with self.assertRaises(ImportError):
410+
from os import does_not_exist
411+
412+
with self.assertRaises(AttributeError):
413+
os.does_not_exist
414+
403415
def test_concurrency(self):
404416
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'data'))
405417
try:
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix assertion failures in case of failing to import from a module with a bad
2+
``__name__`` attribute, and in case of failing to access an attribute of such
3+
a module. Patch by Oren Milman.

Objects/moduleobject.c

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -687,14 +687,11 @@ module_getattro(PyModuleObject *m, PyObject *name)
687687
if (m->md_dict) {
688688
_Py_IDENTIFIER(__name__);
689689
mod_name = _PyDict_GetItemId(m->md_dict, &PyId___name__);
690-
if (mod_name) {
690+
if (mod_name && PyUnicode_Check(mod_name)) {
691691
PyErr_Format(PyExc_AttributeError,
692692
"module '%U' has no attribute '%U'", mod_name, name);
693693
return NULL;
694694
}
695-
else if (PyErr_Occurred()) {
696-
PyErr_Clear();
697-
}
698695
}
699696
PyErr_Format(PyExc_AttributeError,
700697
"module has no attribute '%U'", name);

Python/ceval.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4930,6 +4930,10 @@ import_from(PyObject *v, PyObject *name)
49304930
if (pkgname == NULL) {
49314931
goto error;
49324932
}
4933+
if (!PyUnicode_Check(pkgname)) {
4934+
Py_CLEAR(pkgname);
4935+
goto error;
4936+
}
49334937
fullmodname = PyUnicode_FromFormat("%U.%U", pkgname, name);
49344938
if (fullmodname == NULL) {
49354939
Py_DECREF(pkgname);

0 commit comments

Comments
 (0)