[Python-checkins] [3.8] bpo-37409: fix relative import with no parent (GH-14956) (GH-15913)

Miss Islington (bot) webhook-mailer at python.org
Wed Sep 11 08:50:19 EDT 2019


https://github.com/python/cpython/commit/f3480ad08823a9bc7df490bb5b54593d9483be70
commit: f3480ad08823a9bc7df490bb5b54593d9483be70
branch: 3.7
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: GitHub <noreply at github.com>
date: 2019-09-11T05:50:14-07:00
summary:

[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 92420b3e679959a7d0ce875875601a4cee45231e)

Co-authored-by: Ben Lewis <benjimin at users.noreply.github.com>
(cherry picked from commit 0a6693a469cfb1dd5c8048d8cb4231a7b5883251)

Co-authored-by: Brett Cannon <54418+brettcannon at users.noreply.github.com>

files:
A Misc/NEWS.d/next/Core and Builtins/2019-08-06-23-39-05.bpo-37409.1qwzn2.rst
M Lib/test/test_builtin.py
M Lib/test/test_import/__init__.py
M Misc/ACKS
M Python/import.c

diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py
index e0d2a698dcff..5216da459f67 100644
--- a/Lib/test/test_builtin.py
+++ b/Lib/test/test_builtin.py
@@ -154,6 +154,10 @@ def test_import(self):
         self.assertRaises(TypeError, __import__, 1, 2, 3, 4)
         self.assertRaises(ValueError, __import__, '')
         self.assertRaises(TypeError, __import__, 'sys', name='sys')
+        # Relative import outside of a package with no __package__ or __spec__ (bpo-37409).
+        self.assertRaises(ImportError, __import__, '',
+                          {'__package__': None, '__spec__': None, '__name__': '__main__'},
+                          locals={}, fromlist=('foo',), level=1)
         # embedded null character
         self.assertRaises(ModuleNotFoundError, __import__, 'string\x00')
 
diff --git a/Lib/test/test_import/__init__.py b/Lib/test/test_import/__init__.py
index 1fc4de11e178..4b9907d5329d 100644
--- a/Lib/test/test_import/__init__.py
+++ b/Lib/test/test_import/__init__.py
@@ -711,6 +711,11 @@ def check_relative():
         ns = dict(__package__=object())
         self.assertRaises(TypeError, check_relative)
 
+    def test_parentless_import_shadowed_by_global(self):
+        # Test as if this were done from the REPL where this error most commonly occurs (bpo-37409).
+        script_helper.assert_python_failure('-W', 'ignore', '-c',
+            "foo = 1; from . import foo")
+
     def test_absolute_import_without_future(self):
         # If explicit relative import syntax is used, then do not try
         # to perform an absolute import in the face of failure.
diff --git a/Misc/ACKS b/Misc/ACKS
index c7d6f6c35b61..35fcec2b2088 100644
--- a/Misc/ACKS
+++ b/Misc/ACKS
@@ -949,6 +949,7 @@ Alain Leufroy
 Mark Levinson
 Mark Levitt
 Ivan Levkivskyi
+Ben Lewis
 William Lewis
 Akira Li
 Robert Li
diff --git a/Misc/NEWS.d/next/Core and Builtins/2019-08-06-23-39-05.bpo-37409.1qwzn2.rst b/Misc/NEWS.d/next/Core and Builtins/2019-08-06-23-39-05.bpo-37409.1qwzn2.rst
new file mode 100644
index 000000000000..9cfa71548020
--- /dev/null
+++ b/Misc/NEWS.d/next/Core and Builtins/2019-08-06-23-39-05.bpo-37409.1qwzn2.rst	
@@ -0,0 +1,2 @@
+Ensure explicit relative imports from interactive sessions and scripts (having no parent package) always raise ImportError, rather than treating the current module as the package.
+Patch by Ben Lewis.
diff --git a/Python/import.c b/Python/import.c
index 63c99ea5c1ab..edc59249622b 100644
--- a/Python/import.c
+++ b/Python/import.c
@@ -1563,22 +1563,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) {
@@ -1604,6 +1602,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;



More information about the Python-checkins mailing list