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

Function create_modules

Lib/test/test_importlib/util.py:334–388  ·  view source on GitHub ↗

Temporarily create each named module with an attribute (named 'attr') that contains the name passed into the context manager that caused the creation of the module. All files are created in a temporary directory returned by tempfile.mkdtemp(). This directory is inserted at the begin

(*names)

Source from the content-addressed store, hash-verified

332
333@contextlib.contextmanager
334def create_modules(*names):
335 """Temporarily create each named module with an attribute (named 'attr')
336 that contains the name passed into the context manager that caused the
337 creation of the module.
338
339 All files are created in a temporary directory returned by
340 tempfile.mkdtemp(). This directory is inserted at the beginning of
341 sys.path. When the context manager exits all created files (source and
342 bytecode) are explicitly deleted.
343
344 No magic is performed when creating packages! This means that if you create
345 a module within a package you must also create the package's __init__ as
346 well.
347
348 """
349 source = 'attr = {0!r}'
350 created_paths = []
351 mapping = {}
352 state_manager = None
353 uncache_manager = None
354 try:
355 temp_dir = tempfile.mkdtemp()
356 mapping['.root'] = temp_dir
357 import_names = set()
358 for name in names:
359 if not name.endswith('__init__'):
360 import_name = name
361 else:
362 import_name = name[:-len('.__init__')]
363 import_names.add(import_name)
364 if import_name in sys.modules:
365 del sys.modules[import_name]
366 name_parts = name.split('.')
367 file_path = temp_dir
368 for directory in name_parts[:-1]:
369 file_path = os.path.join(file_path, directory)
370 if not os.path.exists(file_path):
371 os.mkdir(file_path)
372 created_paths.append(file_path)
373 file_path = os.path.join(file_path, name_parts[-1] + '.py')
374 with open(file_path, 'w', encoding='utf-8') as file:
375 file.write(source.format(name))
376 created_paths.append(file_path)
377 mapping[name] = file_path
378 uncache_manager = uncache(*import_names)
379 uncache_manager.__enter__()
380 state_manager = import_state(path=[temp_dir])
381 state_manager.__enter__()
382 yield mapping
383 finally:
384 if state_manager is not None:
385 state_manager.__exit__(None, None, None)
386 if uncache_manager is not None:
387 uncache_manager.__exit__(None, None, None)
388 os_helper.rmtree(temp_dir)
389
390
391def mock_path_hook(*entries, importer):

Callers

nothing calls this directly

Calls 15

setFunction · 0.85
uncacheFunction · 0.85
import_stateFunction · 0.85
mkdtempMethod · 0.80
openFunction · 0.50
endswithMethod · 0.45
addMethod · 0.45
splitMethod · 0.45
joinMethod · 0.45
existsMethod · 0.45
mkdirMethod · 0.45
appendMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…