YAML

suggest change

YAML (YAML Ain't Markup Language) is a human-readable data serialization standard widely used for application configuration, infrastructure-as-code (Kubernetes manifests, Docker Compose, GitHub Actions), and data interchange. In Python, YAML processing is primarily performed using the PyYAML library and the round-trip preserving ruamel.yaml package.


1. Installing PyYAML

PyYAML is not part of Python's standard library. Install it using pip:

pip install pyyaml

Import it as yaml:

import yaml

2. Loading YAML: The Critical Security Rule (safe_load)

The Vulnerability of yaml.load

PyYAML's full loader (yaml.load) is capable of instantiating arbitrary Python objects using YAML tags such as !!python/object/apply:os.system. Calling yaml.load on untrusted input can result in Remote Code Execution (RCE).

CRITICAL RULE: Always use yaml.safe_load() (or specify Loader=yaml.SafeLoader). safe_load restricts parsing to standard scalar types, lists, and dictionaries.

Parsing YAML Strings and Files

import yaml

yaml_data = """
server:
  host: 0.0.0.0
  port: 8080
  debug: true
database:
  name: production_db
  pool_size: 20
tags:
  - web
  - api
  - primary
"""

# Parsing from a string
config = yaml.safe_load(yaml_data)

print(config["server"]["port"])    # Output: 8080
print(config["server"]["debug"])   # Output: True (bool)
print(config["tags"])              # Output: ['web', 'api', 'primary']

Reading Directly from a File

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

Parsing Multiple Documents (safe_load_all)

YAML files (such as Kubernetes manifests) often separate multiple documents with ---. Use yaml.safe_load_all to obtain a generator of documents:

multi_doc_yaml = """
apiVersion: v1
kind: Service
metadata:
  name: web-service
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web-deployment
"""

for doc in yaml.safe_load_all(multi_doc_yaml):
    print(f"Kind: {doc['kind']}, Name: {doc['metadata']['name']}")

3. Dumping Data to YAML (yaml.dump)

Convert Python dictionaries and lists to YAML strings using yaml.dump:

import yaml

data = {
    "app": "OrderService",
    "version": "2.4.0",
    "dependencies": ["redis", "postgres"],
    "settings": {
        "timeout_seconds": 30,
        "retry_enabled": True,
    }
}

# Dump to string
yaml_str = yaml.dump(
    data,
    sort_keys=False,           # Preserve dictionary insertion order
    default_flow_style=False,  # Force block style (indented) instead of JSON-like inline style
    indent=2                   # 2-space indentation
)

print(yaml_str)

Output:

app: OrderService
version: 2.4.0
dependencies:
- redis
- postgres
settings:
  timeout_seconds: 30
  retry_enabled: true

Writing to a File

with open("export.yaml", "w", encoding="utf-8") as f:
    yaml.dump(data, f, sort_keys=False, default_flow_style=False)

4. Preserving Comments with ruamel.yaml

PyYAML discards comments and original formatting when loading and dumping. When you need to read, modify a single key, and save back without destroying existing comments or formatting, use ruamel.yaml:

pip install ruamel.yaml
from ruamel.yaml import YAML

yaml = YAML()
yaml.preserve_quotes = True
yaml.indent(mapping=2, sequence=4, offset=2)

content = """
# Application configuration
server:
  port: 8080 # Production port
  enabled: true
"""

# Load with comments intact
data = yaml.load(content)

# Modify value
data["server"]["port"] = 9000

# Dump back: comment '# Production port' is preserved!
import io
stream = io.StringIO()
yaml.dump(data, stream)
print(stream.getvalue())

5. YAML Quirks to Watch Out For

  1. The Norway Problem: In YAML 1.1, the unquoted string NO (the country code for Norway) evaluates to boolean False. Always quote two-letter country codes: "NO".
  2. Version Numbers as Floats: A version string like version: 3.10 will be parsed as float 3.1. Quote version numbers explicitly: version: "3.10".
  3. Tab Characters Are Forbidden: The YAML specification prohibits tab characters for indentation; use spaces only.

Best Practices

  1. Always Use yaml.safe_load: Never use unconstrained yaml.load on external or untrusted files.
  2. Set sort_keys=False: Retain natural logical ordering when serializing dictionaries.
  3. Always Explicitly Set UTF-8 Encoding: When reading or writing YAML files on Windows and Linux, specify encoding="utf-8" to avoid OS encoding differences.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents