yaml_utils.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import logging
  2. from pathlib import Path
  3. from typing import Any
  4. import yaml # type: ignore
  5. from yaml import YAMLError
  6. logger = logging.getLogger(__name__)
  7. def load_yaml_file(file_path: str, ignore_error: bool = True, default_value: Any = {}) -> Any:
  8. """
  9. Safe loading a YAML file
  10. :param file_path: the path of the YAML file
  11. :param ignore_error:
  12. if True, return default_value if error occurs and the error will be logged in debug level
  13. if False, raise error if error occurs
  14. :param default_value: the value returned when errors ignored
  15. :return: an object of the YAML content
  16. """
  17. if not file_path or not Path(file_path).exists():
  18. if ignore_error:
  19. return default_value
  20. else:
  21. raise FileNotFoundError(f"File not found: {file_path}")
  22. with open(file_path, encoding="utf-8") as yaml_file:
  23. try:
  24. yaml_content = yaml.safe_load(yaml_file)
  25. return yaml_content or default_value
  26. except Exception as e:
  27. if ignore_error:
  28. return default_value
  29. else:
  30. raise YAMLError(f"Failed to load YAML file {file_path}: {e}") from e