[Python-checkins] cpython: importlib.__import__() now raises ValueError when level < 0.

brett.cannon python-checkins at python.org
Fri Feb 17 00:03:52 CET 2012


http://hg.python.org/cpython/rev/45a2bbf6c752
changeset:   74992:45a2bbf6c752
parent:      74983:03140936913c
user:        Brett Cannon <brett at python.org>
date:        Thu Feb 16 17:47:48 2012 -0500
summary:
  importlib.__import__() now raises ValueError when level < 0.
This is to bring it more in line with what PEP 328 set out to do with
removing ambiguous absolute/relative import semantics.

files:
  Lib/importlib/_bootstrap.py            |  2 ++
  Lib/importlib/test/import_/test_api.py |  7 +++++++
  Misc/NEWS                              |  3 +++
  3 files changed, 12 insertions(+), 0 deletions(-)


diff --git a/Lib/importlib/_bootstrap.py b/Lib/importlib/_bootstrap.py
--- a/Lib/importlib/_bootstrap.py
+++ b/Lib/importlib/_bootstrap.py
@@ -1048,6 +1048,8 @@
         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)
diff --git a/Lib/importlib/test/import_/test_api.py b/Lib/importlib/test/import_/test_api.py
--- a/Lib/importlib/test/import_/test_api.py
+++ b/Lib/importlib/test/import_/test_api.py
@@ -12,6 +12,13 @@
         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
diff --git a/Misc/NEWS b/Misc/NEWS
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -466,6 +466,9 @@
 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().

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


More information about the Python-checkins mailing list