INNER CODE UNIT · Python
_import_module
phillipdupuis/pydantic-to-typescript · pydantic2ts/cli/script.py:41
def _import_module(path: str) -> ModuleType:
"""
Helper which allows modules to be specified by either dotted path notation or by filepath.
If we import by filepath, we must also assign a name to it and add it to sys.modules BEFORE
calling 'spec.loader.exec_module' because there is code in pydantic which requires that the
definition exist in sys.modules under that name.
"""
try:
if os.path.exists(path):
name = uuid4().hex
spec = spec_from_file_location(name, path, submodule_search_locations=[])
assert spec is not None, f"spec_from_file_location failed for {path}"
module = module_from_spec(spec)
sys.modules[name] = module
assert spec.loader is not None, f"loader is None for {path}"
spec.loader.exec_module(module)
return module