[Python-checkins] cpython (3.5): Fix a scoping issue where an UnboundLocalError was triggered if a

brett.cannon python-checkins at python.org
Sat Jun 25 13:50:29 EDT 2016


https://hg.python.org/cpython/rev/07a68800be99
changeset: 102167:07a68800be99
branch: 3.5
parent: 102162:a9c21bc3c905
user: Brett Cannon <brett at python.org>
date: Sat Jun 25 10:47:53 2016 -0700
summary:
 Fix a scoping issue where an UnboundLocalError was triggered if a
lazy-loaded module was already in sys.modules.
files:
 Lib/importlib/util.py | 2 +-
 Lib/test/test_importlib/test_lazy.py | 16 +++++++++++++---
 Misc/NEWS | 4 ++++
 3 files changed, 18 insertions(+), 4 deletions(-)
diff --git a/Lib/importlib/util.py b/Lib/importlib/util.py
--- a/Lib/importlib/util.py
+++ b/Lib/importlib/util.py
@@ -241,7 +241,7 @@
 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)
diff --git a/Lib/test/test_importlib/test_lazy.py b/Lib/test/test_importlib/test_lazy.py
--- a/Lib/test/test_importlib/test_lazy.py
+++ b/Lib/test/test_importlib/test_lazy.py
@@ -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 @@
 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()
diff --git a/Misc/NEWS b/Misc/NEWS
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -13,6 +13,10 @@
 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
-- 
Repository URL: https://hg.python.org/cpython


More information about the Python-checkins mailing list

AltStyle によって変換されたページ (->オリジナル) /