From 0f80e9d5e61623624b3fe8cde9216a46fa50cb61 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Mon, 18 May 2020 21:04:38 +0100 Subject: [PATCH] ok, seems that import_dir is a bit saner --- my/core/common.py | 6 ++++++ my/demo.py | 4 ++-- tests/demo.py | 9 ++++++++- 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/my/core/common.py b/my/core/common.py index 985ca67..77ac086 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -9,6 +9,7 @@ import warnings # some helper functions PathIsh = Union[Path, str] +# TODO only used in tests? not sure if useful at all. # TODO port annotations to kython?.. def import_file(p: PathIsh, name: Optional[str]=None) -> types.ModuleType: p = Path(p) @@ -33,6 +34,11 @@ def import_from(path: PathIsh, name: str) -> types.ModuleType: sys.path.remove(path) +def import_dir(path: PathIsh) -> types.ModuleType: + p = Path(path) + return import_from(p.parent, p.name) + + T = TypeVar('T') K = TypeVar('K') V = TypeVar('V') diff --git a/my/demo.py b/my/demo.py index 5fd8ea8..3a9d1b3 100644 --- a/my/demo.py +++ b/my/demo.py @@ -24,8 +24,8 @@ class demo(user_config): def external_module(self): rpath = self.external if rpath is not None: - from .cfg import set_repo - set_repo('external', rpath) + from .core.common import import_dir + return import_dir(rpath) import my.config.repos.external as m # type: ignore return m diff --git a/tests/demo.py b/tests/demo.py index 280eab2..9da5966 100644 --- a/tests/demo.py +++ b/tests/demo.py @@ -104,7 +104,14 @@ def prepare(tmp_path: Path): ''') ext = tmp_path / 'external' ext.mkdir() - (ext / '__init__.py').write_text('identity = lambda x: x') + (ext / '__init__.py').write_text(''' +def identity(x): + from .submodule import hello + hello(x) + return x + +''') + (ext / 'submodule.py').write_text('hello = lambda x: print("hello " + str(x))') yield ex = 'my.config.repos.external' if ex in sys.modules: