@@ -140,19 +140,23 @@ def find_spec(
140140 target : types .ModuleType | None = None ,
141141 ) -> ModuleSpec | None :
142142
143+ debug (f'Consulting InstrumentingFinder.find_spec for fullname={ fullname } ' )
143144 # 1) The fullname is the name of the main module. This might be a dotted name such as x.y.z.py
144145 # so we have special logic here
145146 fp = os .path .join (self .modDir , f"{ fullname } .py" )
146147 if self .mainModName == fullname and os .path .isfile (fp ):
147148 loader = InstrumentingLoader (fullname , fp )
148- return spec_from_file_location (fullname , fp , loader = loader )
149+ spec = spec_from_file_location (fullname , fp , loader = loader )
150+ debug (f'spec for { fullname } : { spec } ' )
151+ return spec
149152 # 2) The fullname is a prefix of the main module. We want to load main modules with
150153 # dotted names such as x.y.z.py, hence we synthesize a namespace pkg
151154 # e.g. if 'x.y.z.py' exists and we're asked for 'x', return a package spec.
152155 elif self .mainModName .startswith (fullname + '.' ):
153156 spec = importlib .machinery .ModuleSpec (fullname , loader = None , is_package = True )
154157 # Namespace package marker (PEP 451)
155158 spec .submodule_search_locations = []
159+ debug (f'spec for { fullname } : { spec } ' )
156160 return spec
157161 # 3) Fallback: use the original PathFinder
158162 spec = self ._origFinder .find_spec (fullname , path , target )
@@ -191,10 +195,19 @@ def setupFinder(modDir: str, modName: str, extraDirs: list[str], typechecking: b
191195 # Create and install our custom finder
192196 instrumenting_finder = InstrumentingFinder (finder , modDir , modName , extraDirs )
193197 sys .meta_path .insert (0 , instrumenting_finder )
198+ debug (f'Installed instrument finder { instrumenting_finder } ' )
199+
200+ alreadyLoaded = sys .modules .get (modName )
201+ if alreadyLoaded :
202+ sys .modules .pop (modName , None )
203+ importlib .invalidate_caches ()
194204
195205 try :
196206 yield
197207 finally :
208+ if alreadyLoaded :
209+ sys .modules [modName ] = alreadyLoaded
210+
198211 # Remove our custom finder when exiting the context
199212 if instrumenting_finder in sys .meta_path :
200213 sys .meta_path .remove (instrumenting_finder )
0 commit comments