Skip to content

Commit eb3cd30

Browse files
committed
Turned out that if you used explicit relative import syntax
(e.g. from .os import sep) and it failed, import would still try the implicit relative import semantics of an absolute import (from os import sep). That's not right, so when level is negative, only do explicit relative import semantics. Fixes issue #7902. Thanks to Meador Inge for the patch.
1 parent b1556c5 commit eb3cd30

3 files changed

Lines changed: 17 additions & 1 deletion

File tree

Lib/test/test_import.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,18 @@ def check_relative():
431431
self.assertRaises(ValueError, check_absolute)
432432
self.assertRaises(ValueError, check_relative)
433433

434+
def test_absolute_import_without_future(self):
435+
# If absolute import syntax is used, then do not try to perform
436+
# a relative import in the face of failure.
437+
# Issue #7902.
438+
try:
439+
from .os import sep
440+
except ImportError:
441+
pass
442+
else:
443+
self.fail("explicit relative import triggered an "
444+
"implicit relative import")
445+
434446

435447
def test_main(verbose=None):
436448
run_unittest(ImportTests, PycRewritingTests, PathsTests, RelativeImportTests)

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ What's New in Python 2.7 Release Candidate 1?
1212
Core and Builtins
1313
-----------------
1414

15+
- Issue #7902: When using explicit relative import syntax, don't try
16+
implicit relative import semantics.
17+
1518
- Issue #7079: Fix a possible crash when closing a file object while using
1619
it from another thread. Patch by Daniel Stutzbach.
1720

Python/import.c

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2134,7 +2134,8 @@ import_module_level(char *name, PyObject *globals, PyObject *locals,
21342134
if (parent == NULL)
21352135
return NULL;
21362136

2137-
head = load_next(parent, Py_None, &name, buf, &buflen);
2137+
head = load_next(parent, level < 0 ? Py_None : parent, &name, buf,
2138+
&buflen);
21382139
if (head == NULL)
21392140
return NULL;
21402141

0 commit comments

Comments
 (0)