Type stubs for PyYAML, a full-featured YAML framework for Python
Functions for serializing Python objects to YAML with different safety levels and formatting options. These functions convert Python data structures to YAML strings or write them to streams.
Recommended functions for dumping Python objects to YAML. These functions use SafeRepresenter and only serialize standard Python types.
def safe_dump(
data: Any,
stream: IO[str] | None = None,
*,
default_style: str | None = None,
default_flow_style: bool | None = None,
canonical: bool | None = None,
indent: int | None = None,
width: int | None = None,
allow_unicode: bool | None = None,
line_break: str | None = None,
encoding: str | None = None,
explicit_start: bool | None = None,
explicit_end: bool | None = None,
version: tuple[int, int] | None = None,
tags: dict[str, str] | None = None,
sort_keys: bool = True
) -> str | None:
"""
Serialize a Python object to YAML using SafeDumper.
Parameters:
- data: Python object to serialize
- stream: Output stream (if None, returns string)
- default_style: Default scalar style (None, '', '"', "'", '|', '>')
- default_flow_style: Use flow style for collections (True/False/None)
- canonical: Produce canonical YAML
- indent: Number of spaces for indentation (default: 2)
- width: Maximum line width (default: 80)
- allow_unicode: Allow unicode characters in output
- line_break: Line break character ('\n', '\r\n', '\r')
- encoding: Output encoding (for streams)
- explicit_start: Add explicit document start marker (---)
- explicit_end: Add explicit document end marker (...)
- version: YAML version tuple
- tags: Tag handle mappings
- sort_keys: Sort mapping keys alphabetically
Returns:
- YAML string if stream is None, otherwise None
Raises:
- YAMLError: If serialization fails
"""
def safe_dump_all(
documents: Sequence[Any],
stream: IO[str] | None = None,
*,
default_style: str | None = None,
default_flow_style: bool | None = None,
canonical: bool | None = None,
indent: int | None = None,
width: int | None = None,
allow_unicode: bool | None = None,
line_break: str | None = None,
encoding: str | None = None,
explicit_start: bool | None = None,
explicit_end: bool | None = None,
version: tuple[int, int] | None = None,
tags: dict[str, str] | None = None,
sort_keys: bool = True
) -> str | None:
"""
Serialize multiple Python objects to YAML using SafeDumper.
Parameters:
- documents: Sequence of Python objects to serialize
- (other parameters same as safe_dump)
Returns:
- YAML string with multiple documents if stream is None, otherwise None
Raises:
- YAMLError: If serialization fails
"""Configurable dumping functions that accept custom Dumper classes for advanced use cases.
def dump(
data: Any,
stream: IO[str] | None = None,
Dumper=None,
*,
default_style: str | None = None,
default_flow_style: bool | None = None,
canonical: bool | None = None,
indent: int | None = None,
width: int | None = None,
allow_unicode: bool | None = None,
line_break: str | None = None,
encoding: str | None = None,
explicit_start: bool | None = None,
explicit_end: bool | None = None,
version: tuple[int, int] | None = None,
tags: dict[str, str] | None = None,
sort_keys: bool = True
) -> str | None:
"""
Serialize a Python object to YAML using specified Dumper.
Parameters:
- data: Python object to serialize
- stream: Output stream (if None, returns string)
- Dumper: Dumper class to use (defaults to SafeDumper)
- (other parameters same as safe_dump)
Returns:
- YAML string if stream is None, otherwise None
Raises:
- YAMLError: If serialization fails
"""
def dump_all(
documents: Sequence[Any],
stream: IO[str] | None = None,
Dumper=None,
*,
default_style: str | None = None,
default_flow_style: bool | None = None,
canonical: bool | None = None,
indent: int | None = None,
width: int | None = None,
allow_unicode: bool | None = None,
line_break: str | None = None,
encoding: str | None = None,
explicit_start: bool | None = None,
explicit_end: bool | None = None,
version: tuple[int, int] | None = None,
tags: dict[str, str] | None = None,
sort_keys: bool = True
) -> str | None:
"""
Serialize multiple Python objects to YAML using specified Dumper.
Parameters:
- documents: Sequence of Python objects to serialize
- stream: Output stream (if None, returns string)
- Dumper: Dumper class to use (defaults to SafeDumper)
- (other parameters same as safe_dump)
Returns:
- YAML string with multiple documents if stream is None, otherwise None
Raises:
- YAMLError: If serialization fails
"""import yaml
data = {
'name': 'John Doe',
'age': 30,
'skills': ['Python', 'YAML', 'Docker'],
'active': True,
'score': 95.5
}
# Dump to string
yaml_string = yaml.safe_dump(data)
print(yaml_string)
# Output:
# age: 30
# active: true
# name: John Doe
# score: 95.5
# skills:
# - Python
# - YAML
# - Docker
# Dump to file
with open('output.yaml', 'w') as file:
yaml.safe_dump(data, file)import yaml
data = {'items': [1, 2, 3], 'nested': {'key': 'value'}}
# Block style (default)
block_yaml = yaml.safe_dump(data, default_flow_style=False)
print(block_yaml)
# items:
# - 1
# - 2
# - 3
# nested:
# key: value
# Flow style
flow_yaml = yaml.safe_dump(data, default_flow_style=True)
print(flow_yaml)
# {items: [1, 2, 3], nested: {key: value}}
# Custom indentation
custom_yaml = yaml.safe_dump(data, indent=4, default_flow_style=False)
print(custom_yaml)
# items:
# - 1
# - 2
# - 3
# nested:
# key: valueimport yaml
documents = [
{'name': 'Document 1', 'type': 'config'},
{'name': 'Document 2', 'type': 'data'},
{'name': 'Document 3', 'type': 'settings'}
]
# Dump multiple documents
yaml_string = yaml.safe_dump_all(documents)
print(yaml_string)
# name: Document 1
# type: config
# ---
# name: Document 2
# type: data
# ---
# name: Document 3
# type: settingsimport yaml
data = {
'config': {
'database': {
'host': 'localhost',
'port': 5432,
'credentials': {
'username': 'user',
'password': 'secret'
}
}
}
}
yaml_string = yaml.safe_dump(
data,
default_flow_style=False,
indent=2,
width=120,
allow_unicode=True,
explicit_start=True,
sort_keys=False
)
print(yaml_string)
# ---
# config:
# database:
# host: localhost
# port: 5432
# credentials:
# username: user
# password: secretimport yaml
# Using a specific dumper
yaml_string = yaml.dump(data, Dumper=yaml.SafeDumper)
# Equivalent to safe_dump
yaml_string = yaml.safe_dump(data)import yaml
# Different scalar styles for strings
data = {
'literal': 'This is a\nmultiline\nstring',
'folded': 'This is a long string that should be folded',
'quoted': 'String with "quotes" inside'
}
# Let PyYAML choose styles automatically
auto_yaml = yaml.safe_dump(data)
# Force specific styles (requires custom representer)
# literal: |
# This is a
# multiline
# string
# folded: >
# This is a long string
# that should be folded
# quoted: "String with \"quotes\" inside"Install with Tessl CLI
npx tessl i tessl/pypi-types-pyyaml