lazy_loader.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. super(LazyLoader, self).__init__(name)
  23. def _load(self):
  24. module = importlib.import_module(self.__name__)
  25. self._parent_module_globals[self._local_name] = module
  26. self.__dict__.update(module.__dict__)
  27. return module
  28. def __getattr__(self, item):
  29. module = self._load()
  30. return getattr(module, item)
  31. def __dir__(self):
  32. module = self._load()
  33. return dir(module)