Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 273323c

Browse files
committed
Issue #14592: A relative import will raise a KeyError if __package__
or __name__ are not set in globals. Thanks to Stefan Behnel for the bug report.
1 parent 09b86d1 commit 273323c

3 files changed

Lines changed: 10 additions & 1 deletion

File tree

Lib/importlib/test/import_/test_relative_imports.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,11 @@ def callback(global_):
203203
self.assertEqual(mod.__name__, 'crash.mod')
204204
self.relative_import_test(create, globals_, callback)
205205

206+
def test_relative_import_no_globals(self):
207+
# No globals for a relative import is an error.
208+
with self.assertRaises(KeyError):
209+
import_util.import_('sys', level=1)
210+
206211

207212
def test_main():
208213
from test.support import run_unittest

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ What's New in Python 3.3.0 Alpha 3?
1010
Core and Builtins
1111
-----------------
1212

13+
- Issue #14592: Attempting a relative import w/o __package__ or __name__ set in
14+
globals raises a KeyError.
15+
1316
- Issue #10854: The ImportError raised when an extension module on Windows
1417
fails to import now uses the new path and name attributes from
1518
Issue #1559549.

Python/import.c

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2355,8 +2355,9 @@ PyImport_ImportModuleLevelObject(PyObject *name, PyObject *given_globals,
23552355
}
23562356
}
23572357
else {
2358-
package = _PyDict_GetItemIdWithError(globals, &PyId___name__);
2358+
package = _PyDict_GetItemId(globals, &PyId___name__);
23592359
if (package == NULL) {
2360+
PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
23602361
goto error;
23612362
}
23622363
else if (!PyUnicode_Check(package)) {

0 commit comments

Comments
 (0)