|
1 | 1 | import importlib |
| 2 | +import warnings |
| 3 | + |
2 | 4 | from typing import Any |
3 | 5 |
|
4 | 6 |
|
5 | | -class VariableNotFound(ImportError): |
6 | | - pass |
| 7 | +class VariableNotFound(ImportError): ... # pylint: disable=multiple-statements |
7 | 8 |
|
8 | 9 |
|
9 | 10 | def import_variable(name: str) -> Any: |
| 11 | + if ":" in name: |
| 12 | + return _import_variable(name) |
| 13 | + return _legacy_import_variable(name) |
| 14 | + |
| 15 | + |
| 16 | +def _import_variable(name: str) -> Any: |
| 17 | + module, variable_name = name.split(":") |
| 18 | + if not module: |
| 19 | + raise VariableNotFound(f"{name} not found in available module") |
| 20 | + try: |
| 21 | + module = importlib.import_module(module) |
| 22 | + except ModuleNotFoundError as e: |
| 23 | + raise VariableNotFound(e.msg) from e |
| 24 | + try: |
| 25 | + variable = getattr(module, variable_name) |
| 26 | + except AttributeError as e: |
| 27 | + raise VariableNotFound(e) from e |
| 28 | + return variable |
| 29 | + |
| 30 | + |
| 31 | +def _legacy_import_variable(name: str) -> Any: |
| 32 | + msg = ( |
| 33 | + "importing using only dot will be soon deprecated," |
| 34 | + " use the new path.to.module:variable syntax" |
| 35 | + ) |
| 36 | + warnings.warn(msg, DeprecationWarning) |
10 | 37 | parts = name.split(".") |
11 | 38 | submodule = ".".join(parts[:-1]) |
| 39 | + if not submodule: |
| 40 | + raise VariableNotFound(f"{name} not found in available module") |
12 | 41 | variable_name = parts[-1] |
13 | 42 | try: |
14 | 43 | module = importlib.import_module(submodule) |
15 | 44 | except ModuleNotFoundError as e: |
16 | 45 | raise VariableNotFound(e.msg) from e |
17 | 46 | try: |
18 | | - subclass = getattr(module, variable_name) |
| 47 | + variable = getattr(module, variable_name) |
19 | 48 | except AttributeError as e: |
20 | 49 | raise VariableNotFound(e) from e |
21 | | - return subclass |
| 50 | + return variable |
0 commit comments