utils.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. """Utilities for Python JSON Logger"""
  2. ### IMPORTS
  3. ### ============================================================================
  4. ## Future
  5. from __future__ import annotations
  6. ## Standard Library
  7. import importlib.util
  8. ## Installed
  9. ## Application
  10. from .exception import MissingPackageError
  11. ### FUNCTIONS
  12. ### ============================================================================
  13. def package_is_available(
  14. name: str, *, throw_error: bool = False, extras_name: str | None = None
  15. ) -> bool:
  16. """Determine if the given package is available for import.
  17. Args:
  18. name: Import name of the package to check.
  19. throw_error: Throw an error if the package is unavailable.
  20. extras_name: Extra dependency name to use in `throw_error`'s message.
  21. Raises:
  22. MissingPackageError: When `throw_error` is `True` and the return value would be `False`
  23. Returns:
  24. If the package is available for import.
  25. """
  26. available = importlib.util.find_spec(name) is not None
  27. if not available and throw_error:
  28. raise MissingPackageError(name, extras_name)
  29. return available