File tree Expand file tree Collapse file tree 2 files changed +27
-0
lines changed
Expand file tree Collapse file tree 2 files changed +27
-0
lines changed Original file line number Diff line number Diff 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 :
Original file line number Diff line number Diff 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\n new_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
228250if __name__ == '__main__' :
229251 unittest .main ()
You can’t perform that action at this time.
0 commit comments