Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d868376

Browse files
committed
Merge from 3.5 for issue #24492
2 parents 28c995d + 7c97a05 commit d868376

2 files changed

Lines changed: 25 additions & 7 deletions

File tree

Lib/test/test_import/__init__.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,19 @@ def test_from_import_message_for_existing_module(self):
324324
with self.assertRaisesRegex(ImportError, "^cannot import name 'bogus'"):
325325
from re import bogus
326326

327+
def test_from_import_AttributeError(self):
328+
# Issue #24492: trying to import an attribute that raises an
329+
# AttributeError should lead to an ImportError.
330+
class AlwaysAttributeError:
331+
def __getattr__(self, _):
332+
raise AttributeError
333+
334+
module_name = 'test_from_import_AttributeError'
335+
self.addCleanup(unload, module_name)
336+
sys.modules[module_name] = AlwaysAttributeError()
337+
with self.assertRaises(ImportError):
338+
from test_from_import_AttributeError import does_not_exist
339+
327340

328341
@skip_if_dont_write_bytecode
329342
class FilePermissionTests(unittest.TestCase):

Python/ceval.c

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5085,19 +5085,24 @@ import_from(PyObject *v, PyObject *name)
50855085
sys.modules. */
50865086
PyErr_Clear();
50875087
pkgname = _PyObject_GetAttrId(v, &PyId___name__);
5088-
if (pkgname == NULL)
5089-
return NULL;
5088+
if (pkgname == NULL) {
5089+
goto error;
5090+
}
50905091
fullmodname = PyUnicode_FromFormat("%U.%U", pkgname, name);
50915092
Py_DECREF(pkgname);
5092-
if (fullmodname == NULL)
5093+
if (fullmodname == NULL) {
50935094
return NULL;
5095+
}
50945096
x = PyDict_GetItem(PyImport_GetModuleDict(), fullmodname);
5095-
if (x == NULL)
5096-
PyErr_Format(PyExc_ImportError, "cannot import name %R", name);
5097-
else
5098-
Py_INCREF(x);
50995097
Py_DECREF(fullmodname);
5098+
if (x == NULL) {
5099+
goto error;
5100+
}
5101+
Py_INCREF(x);
51005102
return x;
5103+
error:
5104+
PyErr_Format(PyExc_ImportError, "cannot import name %R", name);
5105+
return NULL;
51015106
}
51025107

51035108
static int

0 commit comments

Comments
 (0)