YAML parser and emitter for Python with complete YAML 1.1 support, Unicode handling, and optional LibYAML bindings for high performance
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Safe YAML operations designed for processing untrusted input. These functions use SafeLoader and SafeDumper which only handle basic YAML types (strings, numbers, booleans, lists, dictionaries, and null values), preventing execution of arbitrary Python code.
Load YAML documents safely by restricting parsing to basic YAML types only. This is the recommended approach for processing YAML from untrusted sources.
def safe_load(stream):
"""
Parse the first YAML document in a stream and produce the corresponding Python object.
Resolve only basic YAML tags. This is known to be safe for untrusted input.
Args:
stream (str | bytes | IO): YAML content as string, bytes, or file-like object
Returns:
Any: Python object representing the YAML document
Raises:
YAMLError: If the document cannot be parsed
MarkedYAMLError: If there's a syntax error with position information
"""
def safe_load_all(stream):
"""
Parse all YAML documents in a stream and produce corresponding Python objects.
Resolve only basic YAML tags. This is known to be safe for untrusted input.
Args:
stream (str | bytes | IO): YAML content containing multiple documents
Yields:
Any: Python objects representing each YAML document
Raises:
YAMLError: If any document cannot be parsed
MarkedYAMLError: If there's a syntax error with position information
"""import yaml
# Load a single document
config = yaml.safe_load("""
database:
host: localhost
port: 5432
name: myapp
credentials:
username: user
password: secret
""")
print(config['database']['host']) # localhost
# Load multiple documents
documents = yaml.safe_load_all("""
---
name: Development Config
database:
host: dev.example.com
---
name: Production Config
database:
host: prod.example.com
""")
for doc in documents:
print(f"Config: {doc['name']}")
print(f"Host: {doc['database']['host']}")Generate YAML output using only basic YAML tags, ensuring the output can be safely processed by any YAML parser.
def safe_dump(data, stream=None, **kwds):
"""
Serialize a Python object into a YAML stream.
Produce only basic YAML tags.
Args:
data (Any): Python object to serialize
stream (IO, optional): Output stream. If None, return as string
**kwds: Additional keyword arguments for formatting
Keyword Arguments:
default_flow_style (bool): Use flow style for collections (default: False)
canonical (bool): Produce canonical YAML (default: False)
indent (int): Number of spaces for indentation (default: 2)
width (int): Maximum line width (default: 80)
allow_unicode (bool): Allow unicode characters (default: True)
line_break (str): Line break character(s) (default: platform default)
encoding (str): Output encoding for byte streams (default: 'utf-8')
explicit_start (bool): Write document start marker (default: False)
explicit_end (bool): Write document end marker (default: False)
version (tuple): YAML version to use (default: (1, 1))
tags (dict): Custom tag mappings
sort_keys (bool): Sort dictionary keys (default: True)
Returns:
str | None: YAML string if stream is None, otherwise None
Raises:
RepresenterError: If an object cannot be represented
"""
def safe_dump_all(documents, stream=None, **kwds):
"""
Serialize a sequence of Python objects into a YAML stream.
Produce only basic YAML tags.
Args:
documents (Iterable[Any]): Sequence of Python objects to serialize
stream (IO, optional): Output stream. If None, return as string
**kwds: Additional keyword arguments (same as safe_dump)
Returns:
str | None: YAML string if stream is None, otherwise None
Raises:
RepresenterError: If any object cannot be represented
"""import yaml
data = {
'application': 'MyApp',
'version': '1.0.0',
'features': ['auth', 'api', 'ui'],
'settings': {
'debug': False,
'max_connections': 100
}
}
# Dump to string with default formatting
yaml_output = yaml.safe_dump(data)
print(yaml_output)
# Dump with custom formatting
yaml_formatted = yaml.safe_dump(
data,
default_flow_style=False,
indent=4,
width=120,
sort_keys=False
)
print(yaml_formatted)
# Dump multiple documents
documents = [
{'name': 'Config 1', 'value': 100},
{'name': 'Config 2', 'value': 200}
]
yaml_multi = yaml.safe_dump_all(
documents,
explicit_start=True,
explicit_end=False
)
print(yaml_multi)
# Dump to file
with open('config.yaml', 'w') as f:
yaml.safe_dump(data, f, default_flow_style=False)Safe operations support the following Python data types:
str, int, float, bool, Nonelist, tuple, dict| Python Type | YAML Tag | Example |
|---|---|---|
None | !!null | null |
bool | !!bool | true, false |
int | !!int | 42, 0x2A, 0o52 |
float | !!float | 3.14, 1e10, .inf, .nan |
str | !!str | "hello", 'world', plain |
list | !!seq | [1, 2, 3] or block sequence |
dict | !!map | {a: 1, b: 2} or block mapping |
Safe operations provide protection against:
This makes safe operations suitable for:
Install with Tessl CLI
npx tessl i tessl/pypi-pyyaml