- Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathoptional_imports.py
36 lines (27 loc) · 927 Bytes
/
optional_imports.py
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
"""
Stand-alone module to provide information about whether optional deps exist.
"""
fromimportlibimportimport_module
importlogging
importsys
logger=logging.getLogger(__name__)
_not_importable=set()
defget_module(name, should_load=True):
"""
Return module or None. Absolute import is required.
:param (str) name: Dot-separated module path. E.g., 'scipy.stats'.
:raise: (ImportError) Only when exc_msg is defined.
:return: (module|None) If import succeeds, the module will be returned.
"""
ifnotshould_load:
returnsys.modules.get(name, None)
ifnamenotin_not_importable:
try:
returnimport_module(name)
exceptImportError:
_not_importable.add(name)
exceptException:
_not_importable.add(name)
msg=f"Error importing optional module {name}"
logger.exception(msg)
returnNone