MCPcopy Index your code
hub / github.com/python/cpython / CleanImport

Class CleanImport

Lib/test/support/import_helper.py:200–235  ·  view source on GitHub ↗

Context manager to force import to return a new module reference. This is useful for testing module-level behaviours, such as the emission of a DeprecationWarning on import. Use like this: with CleanImport("foo"): importlib.import_module("foo") # new reference

Source from the content-addressed store, hash-verified

198
199
200class CleanImport(object):
201 """Context manager to force import to return a new module reference.
202
203 This is useful for testing module-level behaviours, such as
204 the emission of a DeprecationWarning on import.
205
206 Use like this:
207
208 with CleanImport("foo"):
209 importlib.import_module("foo") # new reference
210
211 If "usefrozen" is False (the default) then the frozen importer is
212 disabled (except for essential modules like importlib._bootstrap).
213 """
214
215 def __init__(self, *module_names, usefrozen=False):
216 self.original_modules = sys.modules.copy()
217 for module_name in module_names:
218 if module_name in sys.modules:
219 module = sys.modules[module_name]
220 # It is possible that module_name is just an alias for
221 # another module (e.g. stub for modules renamed in 3.x).
222 # In that case, we also need delete the real module to clear
223 # the import cache.
224 if module.__name__ != module_name:
225 del sys.modules[module.__name__]
226 del sys.modules[module_name]
227 self._frozen_modules = frozen_modules(usefrozen)
228
229 def __enter__(self):
230 self._frozen_modules.__enter__()
231 return self
232
233 def __exit__(self, *ignore_exc):
234 sys.modules.update(self.original_modules)
235 self._frozen_modules.__exit__(*ignore_exc)
236
237
238class DirsOnSysPath(object):

Calls

no outgoing calls

Used in the wild real call sites across dependent graphs

searching dependent graphs…