API Reference

PyYAML

YAML parser and emitter for Python where safe_load handles trusted documents and rejects code tags.

Official Documentation ↗
CompatibilityThis documentation covers version v6. Check the official docs for the latest API surface.

Installation

pippip install pyyaml

Methods

YAML parser and emitter for Python where safe_load handles trusted documents and rejects code tags.

Overview

PyYAML is the long-standing YAML implementation for Python. safe_load and safe_dump cover the standard subset, mappings, sequences, scalars, anchors, and aliases, which is everything configuration files need, while refusing the tags that made YAML historically dangerous.

Multi-document streams load through load_all variants, and dump options control flow style, width, and key order. For stricter YAML 1.2 semantics in new projects, ruamel.yaml is the common alternative, but PyYAML remains the default dependency.

Core Methods

The most frequently used entry points, with signatures and runnable examples:

  • yaml.safe_load — Parses YAML into Python objects while refusing tags that construct arbitrary objects.
  • yaml.safe_dump — Emits Python objects as YAML, restricted to safe types, with optional key sorting.
  • yaml.safe_load_all — Iterates multi-document YAML streams separated by — markers.

Usage Notes

  • Standardize on safe_load everywhere and lint against bare load in CI.
  • Quote strings that could be read as booleans or numbers, especially version numbers.
  • Use sort_keys=False when emitting files humans will diff.

Common Pitfalls

  • yaml.load without Loader equals arbitrary object construction; a config file becomes an execution vector.
  • Duplicate keys in mappings silently keep the last value in PyYAML instead of erroring.
  • Norway problem: the string no in an unquoted value becomes False.

FAQ

Why never use yaml.load directly?
Bare yaml.load can construct arbitrary Python objects through tags, which is remote code execution on untrusted input. yaml.safe_load accepts exactly the standard YAML subset: dicts, lists, scalars, dates, and refuses object-construction tags.
Why do my unquoted yes/no values become booleans?
YAML 1.1 scalar rules turn unquoted no, on, off, y, n into booleans and unquoted numbers with leading zeros into octal-ish values. Quote ambiguous strings, "version: "1.2"", or enable a YAML 1.2 parser.
How do I preserve key order in output?
Pass sort_keys=False to safe_dump; otherwise PyYAML sorts mapping keys alphabetically, which churns diffs for configuration files.