Module class that surfaces all objects but only performs associated imports when the objects are requested.
| 667 | |
| 668 | |
| 669 | class _LazyModule(ModuleType): |
| 670 | """ |
| 671 | Module class that surfaces all objects but only performs associated imports when the objects are requested. |
| 672 | """ |
| 673 | |
| 674 | # Very heavily inspired by optuna.integration._IntegrationModule |
| 675 | # https://github.com/optuna/optuna/blob/master/optuna/integration/__init__.py |
| 676 | def __init__(self, name, module_file, import_structure, module_spec=None, extra_objects=None): |
| 677 | super().__init__(name) |
| 678 | self._modules = set(import_structure.keys()) |
| 679 | self._class_to_module = {} |
| 680 | for key, values in import_structure.items(): |
| 681 | for value in values: |
| 682 | self._class_to_module[value] = key |
| 683 | # Needed for autocompletion in an IDE |
| 684 | self.__all__ = list(import_structure.keys()) + list(chain(*import_structure.values())) |
| 685 | self.__file__ = module_file |
| 686 | self.__spec__ = module_spec |
| 687 | self.__path__ = [os.path.dirname(module_file)] |
| 688 | self._objects = {} if extra_objects is None else extra_objects |
| 689 | self._name = name |
| 690 | self._import_structure = import_structure |
| 691 | |
| 692 | # Needed for autocompletion in an IDE |
| 693 | def __dir__(self): |
| 694 | result = super().__dir__() |
| 695 | # The elements of self.__all__ that are submodules may or may not be in the dir already, depending on whether |
| 696 | # they have been accessed or not. So we only add the elements of self.__all__ that are not already in the dir. |
| 697 | for attr in self.__all__: |
| 698 | if attr not in result: |
| 699 | result.append(attr) |
| 700 | return result |
| 701 | |
| 702 | def __getattr__(self, name: str) -> Any: |
| 703 | if name in self._objects: |
| 704 | return self._objects[name] |
| 705 | if name in self._modules: |
| 706 | value = self._get_module(name) |
| 707 | elif name in self._class_to_module.keys(): |
| 708 | module = self._get_module(self._class_to_module[name]) |
| 709 | value = getattr(module, name) |
| 710 | else: |
| 711 | raise AttributeError(f"module {self.__name__} has no attribute {name}") |
| 712 | |
| 713 | setattr(self, name, value) |
| 714 | return value |
| 715 | |
| 716 | def _get_module(self, module_name: str): |
| 717 | try: |
| 718 | return importlib.import_module("." + module_name, self.__name__) |
| 719 | except Exception as e: |
| 720 | raise RuntimeError( |
| 721 | f"Failed to import {self.__name__}.{module_name} because of the following error (look up to see its" |
| 722 | f" traceback):\n{e}" |
| 723 | ) from e |
| 724 | |
| 725 | def __reduce__(self): |
| 726 | return (self.__class__, (self._name, self.__file__, self._import_structure)) |
no outgoing calls
no test coverage detected