yaml.py 1.0 KB

123456789101112131415161718192021222324252627282930313233343536
  1. """Yaml utilities."""
  2. from __future__ import annotations
  3. from pathlib import Path, PurePath
  4. from typing import Any
  5. from yaml import dump as ydump
  6. from yaml import load as yload
  7. try:
  8. from yaml import CSafeDumper as SafeDumper
  9. from yaml import CSafeLoader as SafeLoader
  10. except ImportError: # pragma: no cover
  11. from yaml import SafeDumper, SafeLoader # type:ignore[assignment]
  12. def loads(stream: Any) -> Any:
  13. """Load yaml from a stream."""
  14. return yload(stream, Loader=SafeLoader)
  15. def dumps(stream: Any) -> str:
  16. """Parse the first YAML document in a stream as an object."""
  17. return ydump(stream, Dumper=SafeDumper)
  18. def load(fpath: str | PurePath) -> Any:
  19. """Load yaml from a file."""
  20. # coerce PurePath into Path, then read its contents
  21. data = Path(str(fpath)).read_text(encoding="utf-8")
  22. return loads(data)
  23. def dump(data: Any, outpath: str | PurePath) -> None:
  24. """Parse the a YAML document in a file as an object."""
  25. Path(outpath).write_text(dumps(data), encoding="utf-8")