|
1 | 1 | # SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD |
2 | 2 | # SPDX-License-Identifier: Apache-2.0 |
3 | 3 |
|
| 4 | +import importlib |
4 | 5 | import typing as t |
5 | 6 |
|
6 | 7 | from packaging.version import ( |
7 | 8 | Version, |
8 | 9 | ) |
9 | 10 |
|
| 11 | +_ModuleType: t.Any = type(importlib) |
| 12 | + |
| 13 | + |
| 14 | +def lazy_load( |
| 15 | + base_module: _ModuleType, name_obj_dict: t.Dict[str, t.Any], obj_module_dict: t.Dict[str, str] |
| 16 | +) -> t.Callable[[str], t.Any]: |
| 17 | + """ |
| 18 | + use __getattr__ in the __init__.py file to lazy load some objects |
| 19 | +
|
| 20 | + Args: |
| 21 | + base_module (ModuleType): base package module |
| 22 | + name_obj_dict (dict[str, any]): name, real object dict, used to store real objects, |
| 23 | + no need to add lazy-load objects |
| 24 | + obj_module_dict (dict[str, str]): dict of object name and module name |
| 25 | +
|
| 26 | + Returns: |
| 27 | + __getattr__ function |
| 28 | +
|
| 29 | + Example: |
| 30 | +
|
| 31 | + :: |
| 32 | +
|
| 33 | + __getattr__ = lazy_load( |
| 34 | + importlib.import_module(__name__), |
| 35 | + { |
| 36 | + 'IdfApp': IdfApp, |
| 37 | + 'LinuxDut': LinuxDut, |
| 38 | + 'LinuxSerial': LinuxSerial, |
| 39 | + 'CaseTester': CaseTester, |
| 40 | + }, |
| 41 | + { |
| 42 | + 'IdfSerial': '.serial', |
| 43 | + 'IdfDut': '.dut', |
| 44 | + }, |
| 45 | + ) |
| 46 | + """ |
| 47 | + |
| 48 | + def __getattr__(object_name): |
| 49 | + if object_name in name_obj_dict: |
| 50 | + return name_obj_dict[object_name] |
| 51 | + elif object_name in obj_module_dict: |
| 52 | + module = importlib.import_module(obj_module_dict[object_name], base_module.__name__) |
| 53 | + imported = getattr(module, object_name) |
| 54 | + name_obj_dict[object_name] = imported |
| 55 | + return imported |
| 56 | + else: |
| 57 | + raise AttributeError('Attribute %s not found in module %s', object_name, base_module.__name__) |
| 58 | + |
| 59 | + return __getattr__ |
| 60 | + |
10 | 61 |
|
11 | 62 | class InvalidInput(SystemExit): |
12 | 63 | """Invalid input from user""" |
|
0 commit comments