| 35 | globals_ = globals_ or inspect.currentframe().f_back.f_globals |
| 36 | |
| 37 | class LazyModule(object): |
| 38 | def __init__(self): |
| 39 | self._on_loads = [] |
| 40 | |
| 41 | def __getattr__(self, item): |
| 42 | if item.startswith("_pytest") or item in ("__bases__", "__test__"): |
| 43 | raise AttributeError(item) |
| 44 | |
| 45 | real_mod = importlib.import_module(name, package=package) |
| 46 | if rename in globals_: |
| 47 | globals_[rename] = real_mod |
| 48 | elif locals_ is not None: |
| 49 | locals_[rename] = real_mod |
| 50 | ret = getattr(real_mod, item) |
| 51 | for on_load_func in self._on_loads: |
| 52 | on_load_func() |
| 53 | # make sure on_load hooks only executed once |
| 54 | self._on_loads = [] |
| 55 | return ret |
| 56 | |
| 57 | def add_load_handler(self, func: Callable): |
| 58 | self._on_loads.append(func) |
| 59 | return func |
| 60 | |
| 61 | if importlib.util.find_spec(prefix_name) is not None: |
| 62 | return LazyModule() |