Skip to content

Instantly share code, notes, and snippets.

@MG-MW
Created May 15, 2025 07:35
Show Gist options
  • Save MG-MW/f5597a82f6589996eda2f564495571bc to your computer and use it in GitHub Desktop.
Save MG-MW/f5597a82f6589996eda2f564495571bc to your computer and use it in GitHub Desktop.
from importlib.util import module_from_spec, spec_from_file_location
from pathlib import Path
from types import ModuleType
def load_module_from_path(path: Path | str, module_name: str) -> ModuleType:
"""See also
https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
"""
spec = spec_from_file_location(module_name, path)
if spec is None:
raise ValueError(f"No python file found at {path!s}")
if spec.loader is None:
raise ValueError(f"No loader for file at {path!s}")
module = module_from_spec(spec)
spec.loader.exec_module(module)
return module
file_module_path = (
Path("""~/path/to/my/module.py""").expanduser().resolve()
)
mymodule = load_module_from_path(file_module_path, "mymodule")
mymodule.MyClass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment