core.common: move away import related stuff to my.core.utils.imports

moving without backward compatibility, since it's extremely unlikely they are used for any external modules

in fact, unclear if these methods still have much value at all, but keeping for now just in case
This commit is contained in:
Dima Gerasimov 2024-08-14 11:28:50 +03:00
parent f4214807a3
commit 90635c1d67
7 changed files with 44 additions and 43 deletions

37
my/core/utils/imports.py Normal file
View file

@ -0,0 +1,37 @@
import importlib
import importlib.util
from pathlib import Path
import sys
from typing import Optional
from types import ModuleType
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:
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.exec_module(foo)
return foo
def import_from(path: PathIsh, name: str) -> ModuleType:
path = str(path)
sys.path.append(path)
try:
return importlib.import_module(name)
finally:
sys.path.remove(path)
def import_dir(path: PathIsh, extra: str = '') -> ModuleType:
p = Path(path)
if p.parts[0] == '~':
p = p.expanduser() # TODO eh. not sure about this..
return import_from(p.parent, p.name + extra)

View file

@ -105,12 +105,13 @@ else:
def test_listify() -> None:
from ..compat import assert_type
@listify
def it() -> Iterator[int]:
yield 1
yield 2
res = it()
from typing_extensions import assert_type # TODO move to compat?
assert_type(res, List[int])
assert res == [1, 2]