Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e92dc9c

Browse files
committed
Fix a scoping issue where an UnboundLocalError was triggered if a
lazy-loaded module was already in sys.modules.
1 parent 559ad5d commit e92dc9c

3 files changed

Lines changed: 18 additions & 4 deletions

File tree

Lib/importlib/util.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -241,7 +241,7 @@ def __getattribute__(self, attr):
241241
if id(self) != id(sys.modules[original_name]):
242242
msg = ('module object for {!r} substituted in sys.modules '
243243
'during a lazy load')
244-
raise ValueError(msg.format(original_name))
244+
raise ValueError(msg.format(original_name))
245245
# Update after loading since that's what would happen in an eager
246246
# loading situation.
247247
self.__dict__.update(attrs_updated)

Lib/test/test_importlib/test_lazy.py

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import importlib
22
from importlib import abc
33
from importlib import util
4+
import sys
5+
import types
46
import unittest
57

68
from . import util as test_util
@@ -122,12 +124,20 @@ def test_delete_preexisting_attr(self):
122124
self.assertFalse(hasattr(module, '__name__'))
123125

124126
def test_module_substitution_error(self):
125-
source_code = 'import sys; sys.modules[__name__] = 42'
126-
module = self.new_module(source_code)
127127
with test_util.uncache(TestingImporter.module_name):
128-
with self.assertRaises(ValueError):
128+
fresh_module = types.ModuleType(TestingImporter.module_name)
129+
sys.modules[TestingImporter.module_name] = fresh_module
130+
module = self.new_module()
131+
with self.assertRaisesRegex(ValueError, "substituted"):
129132
module.__name__
130133

134+
def test_module_already_in_sys(self):
135+
with test_util.uncache(TestingImporter.module_name):
136+
module = self.new_module()
137+
sys.modules[TestingImporter.module_name] = module
138+
# Force the load; just care that no exception is raised.
139+
module.__name__
140+
131141

132142
if __name__ == '__main__':
133143
unittest.main()

Misc/NEWS

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,10 @@ Core and Builtins
1313
Library
1414
-------
1515

16+
- Fix a scoping issue in importlib.util.LazyLoader which triggered an
17+
UnboundLocalError when lazy-loading a module that was already put into
18+
sys.modules.
19+
1620
- Issue #27079: Fixed curses.ascii functions isblank(), iscntrl() and ispunct().
1721

1822
- Issue #26754: Some functions (compile() etc) accepted a filename argument

0 commit comments

Comments
 (0)