importlib.__import__() now raises ValueError when level < 0.
authorBrett Cannon <brett@python.org>
Thu, 16 Feb 2012 22:47:48 +0000 (17:47 -0500)
committerBrett Cannon <brett@python.org>
Thu, 16 Feb 2012 22:47:48 +0000 (17:47 -0500)
This is to bring it more in line with what PEP 328 set out to do with
removing ambiguous absolute/relative import semantics.

Lib/importlib/_bootstrap.py
Lib/importlib/test/import_/test_api.py
Misc/NEWS

index ad1561efb66900f2f99371a1b2176fc22e394cf3..44349a8e1287a2e0b6ea2e031d88017c72db92be 100644 (file)
@@ -1048,6 +1048,8 @@ def __import__(name, globals={}, locals={}, fromlist=[], level=0):
         raise TypeError("module name must be str, not {}".format(type(name)))
     if level == 0:
         module = _gcd_import(name)
+    elif level < 0:
+        raise ValueError('level must be >= 0')
     else:
         package = _calc___package__(globals)
         module = _gcd_import(name, package, level)
index 9075d4275976fa41346147f455f4d3ff89e9dbe1..2fa1f909547dc350e5130c090bbc56893fe35612 100644 (file)
@@ -12,6 +12,13 @@ class APITest(unittest.TestCase):
         with self.assertRaises(TypeError):
             util.import_(42)
 
+    def test_negative_level(self):
+        # Raise ValueError when a negative level is specified.
+        # PEP 328 did away with sys.module None entries and the ambiguity of
+        # absolute/relative imports.
+        with self.assertRaises(ValueError):
+            util.import_('os', globals(), level=-1)
+
 
 def test_main():
     from test.support import run_unittest
index a1810aee71e296efc8d3d64090f3869f3c6411f5..786417fd6ab74aa84d08f5b31979f8c875db37b5 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -466,6 +466,9 @@ Core and Builtins
 Library
 -------
 
+- Do away with ambiguous level values (as suggested by PEP 328) in
+  importlib.__import__() by raising ValueError when level < 0.
+
 - Issue #2489: pty.spawn could consume 100% cpu when it encountered an EOF.
 
 - Issue #13014: Fix a possible reference leak in SSLSocket.getpeercert().