summaryrefslogtreecommitdiffstats
path: root/Python
diff options
context:
space:
mode:
authorBen Lewis <benjimin@users.noreply.github.com>2019-09-11 10:09:47 (GMT)
committerBrett Cannon <54418+brettcannon@users.noreply.github.com>2019-09-11 10:09:47 (GMT)
commit92420b3e679959a7d0ce875875601a4cee45231e (patch)
tree8e73ad151c044a4233f9b8cfa94127b477a2a33a /Python
parent6472ece5a0fe82809d3aa0ffb281796fcd252d76 (diff)
downloadcpython-92420b3e679959a7d0ce875875601a4cee45231e.zip
cpython-92420b3e679959a7d0ce875875601a4cee45231e.tar.gz
cpython-92420b3e679959a7d0ce875875601a4cee45231e.tar.bz2
bpo-37409: fix relative import with no parent (#14956)
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.
Diffstat (limited to 'Python')
-rw-r--r--Python/import.c24
1 files changed, 13 insertions, 11 deletions
diff --git a/Python/import.c b/Python/import.c
index 41c2f34..5be4d19 100644
--- a/Python/import.c
+++ b/Python/import.c
@@ -1646,23 +1646,20 @@ resolve_name(PyThreadState *tstate, 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(tstate, 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) {
@@ -1688,6 +1685,11 @@ resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level
Py_DECREF(base);
return abs_name;
+ no_parent_error:
+ _PyErr_SetString(tstate, PyExc_ImportError,
+ "attempted relative import "
+ "with no known parent package");
+
error:
Py_XDECREF(package);
return NULL;