_lazy.py 965 B

1234567891011121314151617181920212223242526272829303132
  1. # SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
  2. # SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
  3. # see https://gist.github.com/mara004/6915e904797916b961e9c53b4fc874ec for alternative approaches to deferred imports
  4. import sys
  5. import logging
  6. import functools
  7. logger = logging.getLogger(__name__)
  8. if sys.version_info < (3, 8): # pragma: no cover
  9. # NOTE alternatively, we could write our own cached property backport with python's descriptor protocol
  10. def cached_property(func):
  11. return property( functools.lru_cache(maxsize=1)(func) )
  12. else:
  13. cached_property = functools.cached_property
  14. class _LazyClass:
  15. @cached_property
  16. def PIL_Image(self):
  17. logger.debug("Evaluating lazy import 'PIL.Image' ...")
  18. import PIL.Image; return PIL.Image
  19. @cached_property
  20. def numpy(self):
  21. logger.debug("Evaluating lazy import 'numpy' ...")
  22. import numpy; return numpy
  23. Lazy = _LazyClass()