mirror of
https://github.com/python/cpython.git
synced 2025-07-24 11:44:31 +00:00
bpo-20490: Improve circular import error message (GH-15308)
This commit is contained in:
parent
88b24f96ae
commit
65366bc8bd
5 changed files with 27 additions and 4 deletions
|
@ -1324,6 +1324,16 @@ class CircularImportTests(unittest.TestCase):
|
||||||
self.assertIn('partially initialized module', errmsg)
|
self.assertIn('partially initialized module', errmsg)
|
||||||
self.assertIn('circular import', errmsg)
|
self.assertIn('circular import', errmsg)
|
||||||
|
|
||||||
|
def test_circular_from_import(self):
|
||||||
|
with self.assertRaises(ImportError) as cm:
|
||||||
|
import test.test_import.data.circular_imports.from_cycle1
|
||||||
|
self.assertIn(
|
||||||
|
"cannot import name 'b' from partially initialized module "
|
||||||
|
"'test.test_import.data.circular_imports.from_cycle1' "
|
||||||
|
"(most likely due to a circular import)",
|
||||||
|
str(cm.exception),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
# Test needs to be a package, so we can do relative imports.
|
# Test needs to be a package, so we can do relative imports.
|
||||||
|
|
|
@ -0,0 +1,2 @@
|
||||||
|
from .from_cycle2 import a
|
||||||
|
b = 1
|
|
@ -0,0 +1,2 @@
|
||||||
|
from .from_cycle1 import b
|
||||||
|
a = 1
|
|
@ -0,0 +1,2 @@
|
||||||
|
Improve import error message for partially initialized module on circular
|
||||||
|
``from`` imports - by Anthony Sottile.
|
|
@ -5233,10 +5233,17 @@ import_from(PyThreadState *tstate, PyObject *v, PyObject *name)
|
||||||
PyErr_SetImportError(errmsg, pkgname, NULL);
|
PyErr_SetImportError(errmsg, pkgname, NULL);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
errmsg = PyUnicode_FromFormat(
|
_Py_IDENTIFIER(__spec__);
|
||||||
"cannot import name %R from %R (%S)",
|
PyObject *spec = _PyObject_GetAttrId(v, &PyId___spec__);
|
||||||
name, pkgname_or_unknown, pkgpath
|
Py_XINCREF(spec);
|
||||||
);
|
const char *fmt =
|
||||||
|
_PyModuleSpec_IsInitializing(spec) ?
|
||||||
|
"cannot import name %R from partially initialized module %R "
|
||||||
|
"(most likely due to a circular import) (%S)" :
|
||||||
|
"cannot import name %R from %R (%S)";
|
||||||
|
Py_XDECREF(spec);
|
||||||
|
|
||||||
|
errmsg = PyUnicode_FromFormat(fmt, name, pkgname_or_unknown, pkgpath);
|
||||||
/* NULL checks for errmsg and pkgname done by PyErr_SetImportError. */
|
/* NULL checks for errmsg and pkgname done by PyErr_SetImportError. */
|
||||||
PyErr_SetImportError(errmsg, pkgname, pkgpath);
|
PyErr_SetImportError(errmsg, pkgname, pkgpath);
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue