Repository navigation
Expand file tree
/
Copy pathtry_import.py
More file actions
61 lines (43 loc) · 1.76 KB
/
Copy pathtry_import.py
File metadata and controls
61 lines (43 loc) · 1.76 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from __future__ import annotations
import sys
from contextlib import contextmanager
from dataclasses import dataclass
from types import ModuleType
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Iterator
from typing import Any
@dataclass
class ImportState:
"""Describe whether an optional import succeeded."""
available: bool = True
@contextmanager
def try_import(module_name: str, *symbol_names: str, dependency_name: str) -> Iterator[ImportState]:
"""Context manager to attempt importing symbols into a module.
If the named optional dependency is missing, the symbols are replaced with `FailedImport` objects. Import errors
caused by the importing module itself or by another dependency are propagated instead of being masked.
"""
state = ImportState()
try:
yield state
except ModuleNotFoundError as exc:
if exc.name != dependency_name:
raise
state.available = False
for symbol_name in symbol_names:
setattr(sys.modules[module_name], symbol_name, FailedImport(exc.args[0]))
def install_import_hook(module_name: str) -> None:
"""Install an import hook for a specified module."""
sys.modules[module_name].__class__ = ImportWrapper
@dataclass
class FailedImport:
"""Represent a placeholder for a failed import."""
message: str
"""The error message associated with the failed import."""
class ImportWrapper(ModuleType):
"""A wrapper class for modules to handle attribute access for failed imports."""
def __getattribute__(self, name: str) -> Any:
result = super().__getattribute__(name)
if isinstance(result, FailedImport):
raise ImportError(result.message) # noqa: TRY004
return result