Skip to content

Commit fd952d8

Browse files
committed
fix reload with lazy
1 parent 69cfad0 commit fd952d8

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

Lib/importlib/__init__.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,11 @@ def reload(module):
9797
The module must have been successfully imported before.
9898
9999
"""
100+
# If a LazyModule has not yet been materialized, reload is a no-op.
101+
if importlib_util := sys.modules.get('importlib.util'):
102+
if lazy_module_type := getattr(importlib_util, '_LazyModule', None):
103+
if isinstance(module, lazy_module_type):
104+
return module
100105
try:
101106
name = module.__spec__.name
102107
except AttributeError:

Lib/test/test_importlib/test_lazy.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,28 @@ def __delattr__(self, name):
224224
with self.assertRaises(AttributeError):
225225
del module.CONSTANT
226226

227+
def test_reload(self):
228+
# Reloading a lazy module that hasn't been materialized is a no-op.
229+
module = self.new_module()
230+
sys.modules[TestingImporter.module_name] = module
231+
self.assertIsInstance(module, util._LazyModule)
232+
233+
# Change the source code to add a new attribute
234+
TestingImporter.source_code = 'attr = 42\nnew_attr = 123\n__name__ = {!r}'.format(TestingImporter.mutated_name)
235+
self.assertIsInstance(module, util._LazyModule)
236+
237+
# Reload the module (should be a no-op since not materialized)
238+
reloaded = importlib.reload(module)
239+
self.assertIs(reloaded, module)
240+
self.assertIsInstance(module, util._LazyModule)
241+
242+
243+
# Access the new attribute (should trigger materialization, and new_attr should exist)
244+
self.assertEqual(module.attr, 42)
245+
self.assertNotIsInstance(module, util._LazyModule)
246+
self.assertTrue(hasattr(module, 'new_attr'))
247+
self.assertEqual(module.new_attr, 123)
248+
227249

228250
if __name__ == '__main__':
229251
unittest.main()

0 commit comments

Comments
 (0)