]> granicus.if.org Git - python/commitdiff
Fix a scoping issue where an UnboundLocalError was triggered if a
authorBrett Cannon <brett@python.org>
Sat, 25 Jun 2016 17:47:53 +0000 (10:47 -0700)
committerBrett Cannon <brett@python.org>
Sat, 25 Jun 2016 17:47:53 +0000 (10:47 -0700)
lazy-loaded module was already in sys.modules.

Lib/importlib/util.py
Lib/test/test_importlib/test_lazy.py
Misc/NEWS

index 4525b3f78e46a17e5ea60a9f46e626a8431afeff..e1fa07a6645ea398567657d80fd7e579c518c457 100644 (file)
@@ -241,7 +241,7 @@ class _LazyModule(types.ModuleType):
             if id(self) != id(sys.modules[original_name]):
                 msg = ('module object for {!r} substituted in sys.modules '
                        'during a lazy load')
-            raise ValueError(msg.format(original_name))
+                raise ValueError(msg.format(original_name))
         # Update after loading since that's what would happen in an eager
         # loading situation.
         self.__dict__.update(attrs_updated)
index 774b7a4564119ad48db9ab468d47c6f0ebb17e56..cc383c286dede319e44e57dfd3364869e10e596e 100644 (file)
@@ -1,6 +1,8 @@
 import importlib
 from importlib import abc
 from importlib import util
+import sys
+import types
 import unittest
 
 from . import util as test_util
@@ -122,12 +124,20 @@ class LazyLoaderTests(unittest.TestCase):
         self.assertFalse(hasattr(module, '__name__'))
 
     def test_module_substitution_error(self):
-        source_code = 'import sys; sys.modules[__name__] = 42'
-        module = self.new_module(source_code)
         with test_util.uncache(TestingImporter.module_name):
-            with self.assertRaises(ValueError):
+            fresh_module = types.ModuleType(TestingImporter.module_name)
+            sys.modules[TestingImporter.module_name] = fresh_module
+            module = self.new_module()
+            with self.assertRaisesRegex(ValueError, "substituted"):
                 module.__name__
 
+    def test_module_already_in_sys(self):
+        with test_util.uncache(TestingImporter.module_name):
+            module = self.new_module()
+            sys.modules[TestingImporter.module_name] = module
+            # Force the load; just care that no exception is raised.
+            module.__name__
+
 
 if __name__ == '__main__':
     unittest.main()
index 49304ba38e3fda8cf1f7c52d73680e61fee86eaa..f580afe174ee755dffcde046ba59ef97c828caa0 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -13,6 +13,10 @@ Core and Builtins
 Library
 -------
 
+- Fix a scoping issue in importlib.util.LazyLoader which triggered an
+  UnboundLocalError when lazy-loading a module that was already put into
+  sys.modules.
+
 - Issue #27079: Fixed curses.ascii functions isblank(), iscntrl() and ispunct().
 
 - Issue #26754: Some functions (compile() etc) accepted a filename argument