What it is
PyYAML is a Python library for parsing and writing YAML (YAML Ain’t Markup Language) files. It allows you to read YAML data into Python objects and serialize Python objects back into YAML format.
PyYAML provides functions `yaml.load()` and `yaml.safe_load()` to parse YAML into Python objects, and `yaml.dump()` to serialize Python objects into YAML. `safe_load()` is recommended for untrusted input to avoid executing arbitrary Python objects.
Installation
pip install pyyamlGetting started
The smallest useful thing you can do with it, and what each part means.
import yaml
yaml_str = 'name: Alice\nage: 30\ncity: New York'
data = yaml.safe_load(yaml_str)
print(data)import yaml
with open('config.yaml', 'r') as file:
data = yaml.safe_load(file)
print(data)Advanced usage
Where the library earns its place over a simpler alternative.
import yaml
data = {'name': 'Alice', 'age': 30, 'city': 'New York'}
yaml_str = yaml.dump(data)
print(yaml_str)import yaml
data = {'name': 'Alice', 'age': 30, 'city': 'New York'}
with open('output.yaml', 'w') as file:
yaml.dump(data, file)import yaml
class User:
def __init__(self, name, age):
self.name = name
self.age = age
def user_representer(dumper, data):
return dumper.represent_mapping('!User', {'name': data.name, 'age': data.age})
yaml.add_representer(User, user_representer)
user = User('Alice', 30)
print(yaml.dump(user))import yaml
yaml_str = '---\nname: Alice\n---\nname: Bob'
docs = list(yaml.safe_load_all(yaml_str))
print(docs)Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- yaml.YAMLError
- Raised for any parsing or syntax errors. Check your YAML format for indentation and correct syntax.
- ConstructorError
- Occurs when a custom tag cannot be constructed. Define custom constructors or avoid unsafe tags.
- ScannerError
- Indicates malformed YAML. Ensure correct indentation, colons, and spacing.
Best practices
- Use `safe_load()` instead of `load()` when processing untrusted YAML input.
- Serialize Python objects explicitly using `dump()` with custom representers if needed.
- Keep YAML files human-readable and simple for maintainability.
- Validate parsed YAML data before using it in your application.
- Use `load_all()` to handle multi-document YAML files safely.
Background
Why it exists, and what it was reacting to.
PyYAML was created by Kirill Simonov in 2006 to provide a simple, Pythonic way to work with YAML. YAML is a human-readable data serialization format commonly used for configuration files, data exchange, and application settings. PyYAML quickly became the standard library for YAML processing in Python.
