yaml_utils.py 1.1 KB

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