YAML
suggest changeYAML (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 specifyLoader=yaml.SafeLoader).safe_loadrestricts 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
- The Norway Problem: In YAML 1.1, the unquoted string
NO(the country code for Norway) evaluates to booleanFalse. Always quote two-letter country codes:"NO". - Version Numbers as Floats: A version string like
version: 3.10will be parsed as float3.1. Quote version numbers explicitly:version: "3.10". - Tab Characters Are Forbidden: The YAML specification prohibits tab characters for indentation; use spaces only.
Best Practices
- Always Use
yaml.safe_load: Never use unconstrainedyaml.loadon external or untrusted files. - Set
sort_keys=False: Retain natural logical ordering when serializing dictionaries. - 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.