Install PyYAML (pip install pyyaml), open the file with UTF-8 encoding (open("config.yaml", "r", encoding="utf-8")), and call yaml.safe_load(f)—which safely parses YAML mappings, sequences, scalars, and dates into native Python dict, list, and primitive objects without risking arbitrary code execution.
Basic Example
from pathlib import Path
import yaml
config_path = Path("config.yaml")
# 1. Recommended: Read and parse a single-document YAML file safely
with open(config_path, "r", encoding="utf-8") as f:
data = yaml.safe_load(f)
print(data)
# Example Output: {'app': {'name': 'worker', 'retries': 3, 'debug': False}}
# 2. Parse multi-document YAML files separated by `---`
with open("manifests.yaml", "r", encoding="utf-8") as f:
documents = list(yaml.safe_load_all(f)) # Consume generator before closing file
Key Details & Edge Cases
- Never use
yaml.load(f)withoutLoader=yaml.SafeLoader(critical security vulnerability):- Calling
yaml.load(f)withUnsafeLoaderorFullLoaderon untrusted YAML allows specially crafted tags (such as!!python/object/apply:os.system) to execute arbitrary Python code on your machine. Always useyaml.safe_load(f)(oryaml.load(f, Loader=yaml.SafeLoader)).
- Calling
- Empty YAML files return
None(yaml.safe_load("")$\rightarrow$None):- If a
.yamlfile is completely empty or contains onlycomments,yaml.safe_load(f)returnsNonerather than{}. Normalize withdata = yaml.safe_load(f) or {}when expecting a top-level dictionary.
- If a
- Consume
yaml.safe_load_all(f)inside thewith open(...)block:yaml.safe_load_all(f)returns a lazy generator, not a list. Iterating over it after exiting thewith open(...)block raisesValueError: I/O operation on closed file.Always materialize it vialist(yaml.safe_load_all(f))while the file is still open.
- YAML 1.1 implicit type quirks in PyYAML (
NO,yes,on,12:30):- PyYAML implements the YAML 1.1 specification, which parses unquoted
yes,no,on, andoffas booleans (True/False)—meaning an unquoted country code likecountry: NO(Norway) becomesFalse! Always quote strings like"NO"in YAML 1.1 files, or useruamel.yamlwhen you need strict YAML 1.2 compliance and comment preservation.
- PyYAML implements the YAML 1.1 specification, which parses unquoted
- Handling malformed YAML (
yaml.YAMLError):- Tab characters used for indentation (YAML forbids tabs for indentation—spaces only) or mismatched colons raise
yaml.YAMLError(with.problem_mark.lineand.problem_mark.columnattributes pinpointing the exact syntax error location).
- Tab characters used for indentation (YAML forbids tabs for indentation—spaces only) or mismatched colons raise
Comparison of Python YAML Parsing Libraries & Functions
| Library / Function | Install Package | YAML Spec Version | Preserves Comments & Formatting on Round-Trip? | Best Used When |
|---|---|---|---|---|
yaml.safe_load(f) (Standard) |
pyyaml (import yaml) |
YAML 1.1 | No | Reading standard single-document YAML config files into Python dicts/lists. |
yaml.safe_load_all(f) |
pyyaml (import yaml) |
YAML 1.1 | No | Parsing multi-document YAML streams separated by (e.g., Kubernetes manifests). |
ruamel.yaml (YAML(typ="safe")) |
ruamel.yaml |
YAML 1.2 | Yes (with default round-trip mode) | Modifying YAML files programmatically without stripping comments, or enforcing YAML 1.2 rules. |
strictyaml.load(text) |
strictyaml |
Restricted subset | Yes | Validating typed YAML schemas while blocking implicit type coercion (NO $\rightarrow$ False). |
You must log in or register to comment.
