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 isPyYAML:- Running
pip install yamlfails withERROR: Could not find a version that satisfies the requirement yamlbecauseyamlis only the import name (import yaml), whereas the package distribution name on PyPI isPyYAML.
- Running
- Security critical — NEVER call
yaml.load(text)withoutLoader=yaml.SafeLoader:- In PyYAML 6.0+, calling
yaml.load(data)without an explicitLoader=raisesTypeError: load() missing 1 required positional argument: 'Loader'. Never passyaml.FullLoaderoryaml.UnsafeLoaderto untrusted YAML files, as crafted!!python/object/applytags can execute arbitrary shell commands. Always useyaml.safe_load()(andyaml.safe_dump()for writing).
- In PyYAML 6.0+, calling
- Parsing multi-document YAML files separated by
(yaml.safe_load_all):yaml.safe_load()raisesyaml.composer.ComposerError: expected a single document in the streamif a file contains multiple-delimited documents (such as Kubernetes manifests). Iterate overlist(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/offparse as booleansTrue/False, and country codeNOfor Norway becomesFalse!) and strips all comments on round-trip save. If you need YAML 1.2 rules or comment-preserving file edits, installruamel.yaml(python -m pip install ruamel.yaml).
- PyYAML implements YAML 1.1 (where unquoted
- Missing C compiler /
libyamlwarnings during installation:- PyYAML ships prebuilt binary wheels (with fast C-accelerated
CSafeLoaderincluded) for Windows, macOS, and Linux on PyPI. If installing from source on minimal Linux containers (e.g., Alpine), installgcc,python3-dev, andyaml-devfirst soCSafeLoadercompiles cleanly.
- PyYAML ships prebuilt binary wheels (with fast C-accelerated
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. |
You must log in or register to comment.
