lazy_loader.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # Code copied from https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/util/lazy_loader.py
  15. import importlib
  16. import types
  17. class LazyLoader(types.ModuleType):
  18. """Lazily import a module, mainly to avoid pulling in large dependencies."""
  19. def __init__(self, local_name, parent_module_globals, name):
  20. self._local_name = local_name
  21. self._parent_module_globals = parent_module_globals
  22. self._module = None
  23. super(LazyLoader, self).__init__(name)
  24. @property
  25. def loaded(self):
  26. return self._module is not None
  27. def _load(self):
  28. module = importlib.import_module(self.__name__)
  29. self._parent_module_globals[self._local_name] = module
  30. self._module = module
  31. def __getattr__(self, item):
  32. if not self.loaded:
  33. # HACK: For circumventing shared library symbol conflicts when
  34. # importing paddlex_hpi
  35. if item in ("__file__",):
  36. raise AttributeError
  37. self._load()
  38. return getattr(self._module, item)
  39. def __dir__(self):
  40. if not self.loaded:
  41. self._load()
  42. return dir(self._module)