Skip to content

Commit ab2cb0e

Browse files
committed
bpo-29546: Set name on ImportError for from ... import
And `path` as well when existing. See bpo-29546 This is a step toward providing better error messages in case of from-import. Barry Warsaw Proposed: cannot import name {name} from {module} ({path}) But that's probably going to trigger more discussions that filling in already existing fields.
1 parent 5ec08ce commit ab2cb0e

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

Python/ceval.c

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4995,7 +4995,7 @@ import_from(PyObject *v, PyObject *name)
49954995
{
49964996
PyObject *x;
49974997
_Py_IDENTIFIER(__name__);
4998-
PyObject *fullmodname, *pkgname;
4998+
PyObject *fullmodname, *pkgname, *pkgpath;
49994999

50005000
x = PyObject_GetAttr(v, name);
50015001
if (x != NULL || !PyErr_ExceptionMatches(PyExc_AttributeError))
@@ -5021,7 +5021,15 @@ import_from(PyObject *v, PyObject *name)
50215021
Py_INCREF(x);
50225022
return x;
50235023
error:
5024-
PyErr_Format(PyExc_ImportError, "cannot import name %R", name);
5024+
pkgpath = PyModule_GetFilenameObject(v);
5025+
5026+
if (pkgpath == NULL || !PyUnicode_Check(pkgpath)) {
5027+
PyErr_Clear();
5028+
PyErr_SetImportError(PyUnicode_FromFormat("cannot import name %R", name), pkgname, NULL);
5029+
} else {
5030+
PyErr_SetImportError(PyUnicode_FromFormat("cannot import name %R", name), pkgname, pkgpath);
5031+
}
5032+
50255033
return NULL;
50265034
}
50275035

0 commit comments

Comments
 (0)