[Python-checkins] cpython (merge 3.5 -> default): Merge for issue #26367

brett.cannon python-checkins at python.org
Sat Feb 20 15:59:41 EST 2016


https://hg.python.org/cpython/rev/8f72bf88f471
changeset:   100278:8f72bf88f471
parent:      100276:9955fd3869b6
parent:      100277:e523efd47418
user:        Brett Cannon <brett at python.org>
date:        Sat Feb 20 12:59:36 2016 -0800
summary:
  Merge for issue #26367

files:
  Lib/importlib/_bootstrap.py                              |    5 +-
  Lib/test/test_importlib/import_/test_relative_imports.py |    5 +
  Misc/NEWS                                                |    3 +
  Python/importlib.h                                       |  791 +++++----
  4 files changed, 410 insertions(+), 394 deletions(-)


diff --git a/Lib/importlib/_bootstrap.py b/Lib/importlib/_bootstrap.py
--- a/Lib/importlib/_bootstrap.py
+++ b/Lib/importlib/_bootstrap.py
@@ -922,9 +922,12 @@
         raise TypeError('module name must be str, not {}'.format(type(name)))
     if level < 0:
         raise ValueError('level must be >= 0')
-    if package:
+    if level > 0:
         if not isinstance(package, str):
             raise TypeError('__package__ not set to a string')
+        elif not package:
+            raise ImportError('attempted relative import with no known parent '
+                              'package')
         elif package not in sys.modules:
             msg = ('Parent module {!r} not loaded, cannot perform relative '
                    'import')
diff --git a/Lib/test/test_importlib/import_/test_relative_imports.py b/Lib/test/test_importlib/import_/test_relative_imports.py
--- a/Lib/test/test_importlib/import_/test_relative_imports.py
+++ b/Lib/test/test_importlib/import_/test_relative_imports.py
@@ -218,6 +218,11 @@
             self.__import__('a', {'__package__': '', '__spec__': None},
                             level=1)
 
+    def test_relative_import_no_package_exists_absolute(self):
+        with self.assertRaises(ImportError):
+            self.__import__('sys', {'__package__': '', '__spec__': None},
+                            level=1)
+
 
 (Frozen_RelativeImports,
  Source_RelativeImports
diff --git a/Misc/NEWS b/Misc/NEWS
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -185,6 +185,9 @@
 
 Library
 -------
+- Issue #26367: importlib.__init__() raises ImportError like
+  builtins.__import__() when ``level`` is specified but without an accompanying
+  package specified.
 
 - Issue #26309: In the "socketserver" module, shut down the request (closing
   the connected socket) when verify_request() returns false.  Patch by Aviv
diff --git a/Python/importlib.h b/Python/importlib.h
--- a/Python/importlib.h
+++ b/Python/importlib.h
[stripped]

-- 
Repository URL: https://hg.python.org/cpython


More information about the Python-checkins mailing list