-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathimport_utils.py
More file actions
40 lines (31 loc) · 1.28 KB
/
import_utils.py
File metadata and controls
40 lines (31 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import importlib
from types import SimpleNamespace
from typing import List, Tuple, TypeVar, Union, Iterable, Callable, Optional
U = TypeVar("U")
def __try_names__(name: str, f: Callable[[str], U], prefixes: List[str]) -> U:
try:
return f(name)
except ModuleNotFoundError:
l = prefixes[0]
return __try_names__(l + "." + name, f, prefixes[1:])
def import_file_function(
import_name: str,
keys: Iterable[Union[str, Tuple[str, str]]],
prefixes: List[str] = [],
) -> Callable[[bool], Optional[SimpleNamespace]]:
"""
Utility function that creates a simple loader for you if you only need
> from name.name import X, Y, ...
where "X, Y, ..." are elements of keys.
prefixes is a list of prefixes to the import name to try in case of failure.
"""
def loader(fully_load: bool = True) -> Optional[SimpleNamespace]:
if not fully_load:
return __try_names__(import_name, importlib.util.find_spec, prefixes) # type: ignore
module = __try_names__(import_name, importlib.import_module, prefixes)
out = {}
for key in keys:
get, set = key if isinstance(key, tuple) else (key, key)
out[set] = module.__getattribute__(get)
return SimpleNamespace(**out)
return loader