Skip to content

Instantly share code, notes, and snippets.

@honno
Created February 8, 2022 11:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save honno/4919d89218e34888f091d6b2eb2d9b16 to your computer and use it in GitHub Desktop.
Save honno/4919d89218e34888f091d6b2eb2d9b16 to your computer and use it in GitHub Desktop.
Get module via path
from importlib.util import spec_from_file_location, module_from_spec
from pathlib import Path
from types import ModuleType
def get_mod(path: Path) -> ModuleType:
mod_name = path.name.replace(".py", "")
spec = spec_from_file_location(mod_name, path)
assert spec is not None
mod = module_from_spec(spec)
assert spec.loader is not None
spec.loader.exec_module(mod)
return mod
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment