This commit is contained in:
Dima Gerasimov 2024-10-19 19:15:36 +01:00
parent bc7c3ac253
commit d1511929a8
33 changed files with 117 additions and 117 deletions

View file

@ -1,3 +1,5 @@
from __future__ import annotations
import importlib
import importlib.util
import sys
@ -5,23 +7,22 @@ from pathlib import Path
from types import ModuleType
from typing import Optional
from ..common import PathIsh
# TODO only used in tests? not sure if useful at all.
def import_file(p: PathIsh, name: Optional[str] = None) -> ModuleType:
def import_file(p: Path | str, name: str | None = None) -> ModuleType:
p = Path(p)
if name is None:
name = p.stem
spec = importlib.util.spec_from_file_location(name, p)
assert spec is not None, f"Fatal error; Could not create module spec from {name} {p}"
foo = importlib.util.module_from_spec(spec)
loader = spec.loader; assert loader is not None
loader = spec.loader
assert loader is not None
loader.exec_module(foo)
return foo
def import_from(path: PathIsh, name: str) -> ModuleType:
def import_from(path: Path | str, name: str) -> ModuleType:
path = str(path)
sys.path.append(path)
try:
@ -30,7 +31,7 @@ def import_from(path: PathIsh, name: str) -> ModuleType:
sys.path.remove(path)
def import_dir(path: PathIsh, extra: str = '') -> ModuleType:
def import_dir(path: Path | str, extra: str = '') -> ModuleType:
p = Path(path)
if p.parts[0] == '~':
p = p.expanduser() # TODO eh. not sure about this..