]> granicus.if.org Git - python/commitdiff
Issue #14592: A relative import will raise a KeyError if __package__
authorBrett Cannon <brett@python.org>
Tue, 17 Apr 2012 23:05:11 +0000 (19:05 -0400)
committerBrett Cannon <brett@python.org>
Tue, 17 Apr 2012 23:05:11 +0000 (19:05 -0400)
or __name__ are not set in globals.

Thanks to Stefan Behnel for the bug report.

Lib/importlib/test/import_/test_relative_imports.py
Misc/NEWS
Python/import.c

index 5b4e23c8b2493fe802c033035d1bdff0162e84ef..4569c26424f40104fd29654ce1be6067d87ddc72 100644 (file)
@@ -203,6 +203,11 @@ class RelativeImports(unittest.TestCase):
             self.assertEqual(mod.__name__, 'crash.mod')
         self.relative_import_test(create, globals_, callback)
 
+    def test_relative_import_no_globals(self):
+        # No globals for a relative import is an error.
+        with self.assertRaises(KeyError):
+            import_util.import_('sys', level=1)
+
 
 def test_main():
     from test.support import run_unittest
index f1837e732cf930a4208e6d3ecacbe6072ba0c8d2..9f0009fad83fe8048826c4f709192f7d68e583f1 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -10,6 +10,9 @@ What's New in Python 3.3.0 Alpha 3?
 Core and Builtins
 -----------------
 
+- Issue #14592: Attempting a relative import w/o __package__ or __name__ set in
+  globals raises a KeyError.
+
 - Issue #10854: The ImportError raised when an extension module on Windows
   fails to import now uses the new path and name attributes from
   Issue #1559549.
index f3de7d826278134ba9f59f21e6ff7fb94651ad8a..3e620b37064d819ceb3361555af54e579c44c7fd 100644 (file)
@@ -2355,8 +2355,9 @@ PyImport_ImportModuleLevelObject(PyObject *name, PyObject *given_globals,
             }
         }
         else {
-            package = _PyDict_GetItemIdWithError(globals, &PyId___name__);
+            package = _PyDict_GetItemId(globals, &PyId___name__);
             if (package == NULL) {
+                PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
                 goto error;
             }
             else if (!PyUnicode_Check(package)) {