Install the PyYAML package from PyPI via python -m pip install PyYAML (note that the PyPI distribution name is PyYAML, while the Python import module name is lowercase yaml), and always parse YAML files with yaml.safe_load() rather than yaml.load() to prevent arbitrary code execution.

Basic Example

# 1. Install PyYAML into your active Python environment:
python -m pip install PyYAML
import yaml

yaml_content = """
app:
  name: analytics-service
  port: 8080
  features:
    - auth
    - metrics
"""

# 2. Recommended: Parse YAML safely using `yaml.safe_load()`
config = yaml.safe_load(yaml_content)
print(config["app"]["port"])
# Output: 8080

# 3. Reading from and writing to a UTF-8 YAML file:
with open("config.yaml", "w", encoding="utf-8") as f:
    yaml.safe_dump(config, f, sort_keys=False, allow_unicode=True)

with open("config.yaml", "r", encoding="utf-8") as f:
    loaded = yaml.safe_load(f)

Key Details & Edge Cases

  • Do NOT run pip install yaml — the package on PyPI is PyYAML:
    • Running pip install yaml fails with ERROR: Could not find a version that satisfies the requirement yaml because yaml is only the import name (import yaml), whereas the package distribution name on PyPI is PyYAML.
  • Security critical — NEVER call yaml.load(text) without Loader=yaml.SafeLoader:
    • In PyYAML 6.0+, calling yaml.load(data) without an explicit Loader= raises TypeError: load() missing 1 required positional argument: 'Loader'. Never pass yaml.FullLoader or yaml.UnsafeLoader to untrusted YAML files, as crafted !!python/object/apply tags can execute arbitrary shell commands. Always use yaml.safe_load() (and yaml.safe_dump() for writing).
  • Parsing multi-document YAML files separated by --- (yaml.safe_load_all):
    • yaml.safe_load() raises yaml.composer.ComposerError: expected a single document in the stream if a file contains multiple ----delimited documents (such as Kubernetes manifests). Iterate over list(yaml.safe_load_all(f)) instead.
  • Preserving comments, formatting, and YAML 1.2 compliance (ruamel.yaml):
    • PyYAML implements YAML 1.1 (where unquoted yes/no/on/off parse as booleans True/False, and country code NO for Norway becomes False!) and strips all comments on round-trip save. If you need YAML 1.2 rules or comment-preserving file edits, install ruamel.yaml (python -m pip install ruamel.yaml).
  • Missing C compiler / libyaml warnings during installation:
    • PyYAML ships prebuilt binary wheels (with fast C-accelerated CSafeLoader included) for Windows, macOS, and Linux on PyPI. If installing from source on minimal Linux containers (e.g., Alpine), install gcc, python3-dev, and yaml-dev first so CSafeLoader compiles cleanly.

Comparison of YAML Installation & Parsing Options in Python

Package / Method Install Command Import Name Preserves Comments & YAML 1.2? Best Used When
PyYAML (yaml.safe_load) (Recommended) python -m pip install PyYAML import yaml No (YAML 1.1, strips comments on dump) Standard configuration loading, CI/CD pipelines, and general read/write YAML tasks.
PyYAML (yaml.safe_load_all) python -m pip install PyYAML import yaml No (YAML 1.1) Reading multi-document YAML streams separated by --- (e.g., Kubernetes / Helm manifests).
ruamel.yaml python -m pip install ruamel.yaml from ruamel.yaml import YAML Yes (YAML 1.2 + round-trip comment preservation) Programmatically modifying existing YAML config files without losing comments, quotes, or key order.
yaml on PyPI (Invalid) pip install yaml (Fails) N/A N/A Does not exist on PyPI—always install PyYAML instead.