mirror of
https://github.com/python/cpython.git
synced 2025-08-03 16:39:00 +00:00
[3.8] bpo-37409: fix relative import with no parent (GH-14956) (GH-15913)
Relative imports use resolve_name to get the absolute target name,
which first seeks the current module's absolute package name from the globals:
If __package__ (and __spec__.parent) are missing then
import uses __name__, truncating the last segment if
the module is a submodule rather than a package __init__.py
(which it guesses from whether __path__ is defined).
The __name__ attempt should fail if there is no parent package (top level modules),
if __name__ is '__main__' (-m entry points), or both (scripts).
That is, if both __name__ has no subcomponents and the module does not seem
to be a package __init__ module then import should fail..
(cherry picked from commit 92420b3e67
)
Co-authored-by: Ben Lewis <benjimin@users.noreply.github.com>
This commit is contained in:
parent
0ba5dbd992
commit
0a6693a469
5 changed files with 25 additions and 10 deletions
|
@ -1601,22 +1601,20 @@ resolve_name(PyObject *name, PyObject *globals, int level)
|
|||
if (dot == -2) {
|
||||
goto error;
|
||||
}
|
||||
|
||||
if (dot >= 0) {
|
||||
PyObject *substr = PyUnicode_Substring(package, 0, dot);
|
||||
if (substr == NULL) {
|
||||
goto error;
|
||||
}
|
||||
Py_SETREF(package, substr);
|
||||
else if (dot == -1) {
|
||||
goto no_parent_error;
|
||||
}
|
||||
PyObject *substr = PyUnicode_Substring(package, 0, dot);
|
||||
if (substr == NULL) {
|
||||
goto error;
|
||||
}
|
||||
Py_SETREF(package, substr);
|
||||
}
|
||||
}
|
||||
|
||||
last_dot = PyUnicode_GET_LENGTH(package);
|
||||
if (last_dot == 0) {
|
||||
PyErr_SetString(PyExc_ImportError,
|
||||
"attempted relative import with no known parent package");
|
||||
goto error;
|
||||
goto no_parent_error;
|
||||
}
|
||||
|
||||
for (level_up = 1; level_up < level; level_up += 1) {
|
||||
|
@ -1642,6 +1640,11 @@ resolve_name(PyObject *name, PyObject *globals, int level)
|
|||
Py_DECREF(base);
|
||||
return abs_name;
|
||||
|
||||
no_parent_error:
|
||||
PyErr_SetString(PyExc_ImportError,
|
||||
"attempted relative import "
|
||||
"with no known parent package");
|
||||
|
||||
error:
|
||||
Py_XDECREF(package);
|
||||
return NULL;
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue