Module class that surfaces all objects but only performs associated imports when the objects are requested.
| 788 | |
| 789 | |
| 790 | class _LazyModule(ModuleType): |
| 791 | """ |
| 792 | Module class that surfaces all objects but only performs associated imports when the objects are requested. |
| 793 | """ |
| 794 | |
| 795 | # Very heavily inspired by optuna.integration._IntegrationModule |
| 796 | # https://github.com/optuna/optuna/blob/master/optuna/integration/__init__.py |
| 797 | def __init__(self, name, module_file, import_structure, module_spec=None, extra_objects=None): |
| 798 | super().__init__(name) |
| 799 | self._modules = set(import_structure.keys()) |
| 800 | self._class_to_module = {} |
| 801 | for key, values in import_structure.items(): |
| 802 | for value in values: |
| 803 | self._class_to_module[value] = key |
| 804 | # Needed for autocompletion in an IDE |
| 805 | self.__all__ = list(import_structure.keys()) + list(chain(*import_structure.values())) |
| 806 | self.__file__ = module_file |
| 807 | self.__spec__ = module_spec |
| 808 | self.__path__ = [os.path.dirname(module_file)] |
| 809 | self._objects = {} if extra_objects is None else extra_objects |
| 810 | self._name = name |
| 811 | self._import_structure = import_structure |
| 812 | |
| 813 | # Needed for autocompletion in an IDE |
| 814 | def __dir__(self): |
| 815 | result = super().__dir__() |
| 816 | # The elements of self.__all__ that are submodules may or may not be in the dir already, depending on whether |
| 817 | # they have been accessed or not. So we only add the elements of self.__all__ that are not already in the dir. |
| 818 | for attr in self.__all__: |
| 819 | if attr not in result: |
| 820 | result.append(attr) |
| 821 | return result |
| 822 | |
| 823 | def __getattr__(self, name: str) -> Any: |
| 824 | if name in self._objects: |
| 825 | return self._objects[name] |
| 826 | if name in self._modules: |
| 827 | value = self._get_module(name) |
| 828 | elif name in self._class_to_module.keys(): |
| 829 | module = self._get_module(self._class_to_module[name]) |
| 830 | value = getattr(module, name) |
| 831 | else: |
| 832 | raise AttributeError(f"module {self.__name__} has no attribute {name}") |
| 833 | |
| 834 | setattr(self, name, value) |
| 835 | return value |
| 836 | |
| 837 | def _get_module(self, module_name: str): |
| 838 | try: |
| 839 | return importlib.import_module("." + module_name, self.__name__) |
| 840 | except Exception as e: |
| 841 | raise RuntimeError( |
| 842 | f"Failed to import {self.__name__}.{module_name} because of the following error (look up to see its" |
| 843 | f" traceback):\n{e}" |
| 844 | ) from e |
| 845 | |
| 846 | def __reduce__(self): |
| 847 | return (self.__class__, (self._name, self.__file__, self._import_structure)) |
no outgoing calls
no test coverage detected