Skip to content
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Lib/importlib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,11 @@ def reload(module):
The module must have been successfully imported before.

"""
# If a LazyModule has not yet been materialized, reload is a no-op.
if importlib_util := sys.modules.get('importlib.util'):
if lazy_module_type := getattr(importlib_util, '_LazyModule', None):
if isinstance(module, lazy_module_type):
return module
try:
name = module.__spec__.name
except AttributeError:
Expand Down
25 changes: 25 additions & 0 deletions Lib/test/test_importlib/test_lazy.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
from test.support import threading_helper
from test.test_importlib import util as test_util

# Make sure sys.modules[util] is in sync with the import.
# That is needed as other tests may reload util.
sys.modules['importlib.util'] = util

class CollectInit:

Expand Down Expand Up @@ -224,6 +227,28 @@ def __delattr__(self, name):
with self.assertRaises(AttributeError):
del module.CONSTANT

def test_reload(self):
# Reloading a lazy module that hasn't been materialized is a no-op.
module = self.new_module()
sys.modules[TestingImporter.module_name] = module
self.assertIsInstance(module, util._LazyModule)

# Change the source code to add a new attribute
TestingImporter.source_code = 'attr = 42\nnew_attr = 123\n__name__ = {!r}'.format(TestingImporter.mutated_name)
self.assertIsInstance(module, util._LazyModule)

# Reload the module (should be a no-op since not materialized)
reloaded = importlib.reload(module)
self.assertIs(reloaded, module)
self.assertIsInstance(module, util._LazyModule)


# Access the new attribute (should trigger materialization, and new_attr should exist)
self.assertEqual(module.attr, 42)
self.assertNotIsInstance(module, util._LazyModule)
self.assertTrue(hasattr(module, 'new_attr'))
self.assertEqual(module.new_attr, 123)


if __name__ == '__main__':
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Make importlib.reload no-op for lazy modules.
Loading