MCPcopy Index your code
hub / github.com/RustPython/RustPython / create_modules

Function create_modules

Lib/test/test_importlib/util.py:333–387  ·  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

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

Callers

nothing calls this directly

Calls 15

setFunction · 0.85
lenFunction · 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

Tested by

no test coverage detected