Skip to content
Merged
12 changes: 10 additions & 2 deletions Lib/test/test_import/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -815,6 +815,14 @@ def test_frozen_module_from_import_error(self):
str(cm.exception),
)

expected_error = (
b"cannot import name 'this_will_never_exist' "
b"from 'sys' (unknown location)"
)
popen = script_helper.spawn_python("-c", "from sys import this_will_never_exist")
stdout, stderr = popen.communicate()
self.assertIn(expected_error, stdout)


scripts = [
"""
Expand All @@ -834,11 +842,11 @@ def test_frozen_module_from_import_error(self):
with self.subTest(script=script):
expected_error = (
b"cannot import name 'this_will_never_exist' "
b"from 'os' \\(unknown location\\)"
b"from 'os' (unknown location)"
)
popen = script_helper.spawn_python("-c", script)
stdout, stderr = popen.communicate()
self.assertRegex(stdout, expected_error)
self.assertIn(expected_error, stdout)

def test_script_shadowing_stdlib(self):
script_errors = [
Expand Down
35 changes: 19 additions & 16 deletions Python/ceval.c
Original file line number Diff line number Diff line change
Expand Up @@ -2859,6 +2859,20 @@ _PyEval_ImportFrom(PyThreadState *tstate, PyObject *v, PyObject *name)
}
}

if (origin == NULL) {
// Fall back to __file__ for diagnostics if we don't have
// an origin that is a location
origin = PyModule_GetFilenameObject(v);
if (origin == NULL) {
if (!PyErr_ExceptionMatches(PyExc_SystemError)) {
goto done;
}
// PyModule_GetFilenameObject raised "module filename missing"
_PyErr_Clear(tstate);
}
assert(origin == NULL || PyUnicode_Check(origin));
}

if (is_possibly_shadowing_stdlib) {
assert(origin);
errmsg = PyUnicode_FromFormat(
Expand Down Expand Up @@ -2903,19 +2917,6 @@ _PyEval_ImportFrom(PyThreadState *tstate, PyObject *v, PyObject *name)
}
else {
assert(rc == 0);
if (origin == NULL) {
// Fall back to __file__ for diagnostics if we don't have
// an origin that is a location
origin = PyModule_GetFilenameObject(v);
if (origin == NULL) {
if (!PyErr_ExceptionMatches(PyExc_SystemError)) {
goto done;
}
// PyModule_GetFilenameObject raised "module filename missing"
_PyErr_Clear(tstate);
}
assert(origin == NULL || PyUnicode_Check(origin));
}
if (origin) {
errmsg = PyUnicode_FromFormat(
"cannot import name %R from %R (%S)",
Expand All @@ -2932,9 +2933,11 @@ _PyEval_ImportFrom(PyThreadState *tstate, PyObject *v, PyObject *name)
}

done_with_errmsg:
/* NULL checks for errmsg, mod_name, origin done by PyErr_SetImportError. */
_PyErr_SetImportErrorWithNameFrom(errmsg, mod_name, origin, name);
Py_DECREF(errmsg);
if (errmsg != NULL) {
/* NULL checks for errmsg, mod_name, origin done by _PyErr_SetImportErrorWithNameFrom */
_PyErr_SetImportErrorWithNameFrom(errmsg, mod_name, origin, name);
Py_DECREF(errmsg);
}

done:
Py_XDECREF(origin);
Expand Down
Loading