Skip to content

Commit 65366bc

Browse files
asottilezooba
authored andcommitted
bpo-20490: Improve circular import error message (GH-15308)
1 parent 88b24f9 commit 65366bc

File tree

5 files changed

+27
-4
lines changed

5 files changed

+27
-4
lines changed

Lib/test/test_import/__init__.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1324,6 +1324,16 @@ def test_crossreference2(self):
13241324
self.assertIn('partially initialized module', errmsg)
13251325
self.assertIn('circular import', errmsg)
13261326

1327+
def test_circular_from_import(self):
1328+
with self.assertRaises(ImportError) as cm:
1329+
import test.test_import.data.circular_imports.from_cycle1
1330+
self.assertIn(
1331+
"cannot import name 'b' from partially initialized module "
1332+
"'test.test_import.data.circular_imports.from_cycle1' "
1333+
"(most likely due to a circular import)",
1334+
str(cm.exception),
1335+
)
1336+
13271337

13281338
if __name__ == '__main__':
13291339
# Test needs to be a package, so we can do relative imports.
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
from .from_cycle2 import a
2+
b = 1
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
from .from_cycle1 import b
2+
a = 1
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improve import error message for partially initialized module on circular
2+
``from`` imports - by Anthony Sottile.

Python/ceval.c

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5233,10 +5233,17 @@ import_from(PyThreadState *tstate, PyObject *v, PyObject *name)
52335233
PyErr_SetImportError(errmsg, pkgname, NULL);
52345234
}
52355235
else {
5236-
errmsg = PyUnicode_FromFormat(
5237-
"cannot import name %R from %R (%S)",
5238-
name, pkgname_or_unknown, pkgpath
5239-
);
5236+
_Py_IDENTIFIER(__spec__);
5237+
PyObject *spec = _PyObject_GetAttrId(v, &PyId___spec__);
5238+
Py_XINCREF(spec);
5239+
const char *fmt =
5240+
_PyModuleSpec_IsInitializing(spec) ?
5241+
"cannot import name %R from partially initialized module %R "
5242+
"(most likely due to a circular import) (%S)" :
5243+
"cannot import name %R from %R (%S)";
5244+
Py_XDECREF(spec);
5245+
5246+
errmsg = PyUnicode_FromFormat(fmt, name, pkgname_or_unknown, pkgpath);
52405247
/* NULL checks for errmsg and pkgname done by PyErr_SetImportError. */
52415248
PyErr_SetImportError(errmsg, pkgname, pkgpath);
52425249
}

0 commit comments

Comments
 (0)