Type stubs for PyYAML, a full-featured YAML framework for Python
Configurable loader and dumper classes that combine different processing components for customized YAML processing. These classes provide fine-grained control over the YAML processing pipeline.
Loader classes combine Reader, Scanner, Parser, Composer, Constructor, and Resolver components to provide complete YAML loading functionality.
class BaseLoader(Reader, Scanner, Parser, Composer, BaseConstructor, BaseResolver):
"""
Basic loader combining fundamental processing components.
Constructor parameters:
- stream: Input stream to read from
"""
class SafeLoader(Reader, Scanner, Parser, Composer, SafeConstructor, Resolver):
"""
Safe loader for trusted YAML input.
Only constructs standard YAML tags, preventing arbitrary code execution.
Recommended for loading YAML from untrusted sources.
Constructor parameters:
- stream: Input stream to read from
"""
class FullLoader(Reader, Scanner, Parser, Composer, FullConstructor, Resolver):
"""
Full-featured loader with extended Python object support.
Supports Python objects like tuples, sets, and other built-in types
while remaining safer than UnsafeLoader.
Constructor parameters:
- stream: Input stream to read from
"""
class Loader(Reader, Scanner, Parser, Composer, Constructor, Resolver):
"""
Legacy loader class (alias for SafeLoader in modern PyYAML).
Constructor parameters:
- stream: Input stream to read from
"""
class UnsafeLoader(Reader, Scanner, Parser, Composer, Constructor, Resolver):
"""
Unsafe loader allowing arbitrary Python object construction.
WARNING: Can execute arbitrary Python code. Only use with trusted input.
Constructor parameters:
- stream: Input stream to read from
"""Dumper classes combine Emitter, Serializer, Representer, and Resolver components to provide complete YAML dumping functionality.
class BaseDumper(Emitter, Serializer, BaseRepresenter, BaseResolver):
"""
Basic dumper combining fundamental processing components.
Constructor parameters:
- stream: Output stream to write to
- default_style: Default scalar style
- default_flow_style: Default collection style
- canonical: Produce canonical YAML
- indent: Indentation spaces
- width: Maximum line width
- allow_unicode: Allow unicode characters
- line_break: Line break character
- encoding: Output encoding
- explicit_start: Add document start marker
- explicit_end: Add document end marker
- version: YAML version
- tags: Tag handle mappings
- sort_keys: Sort mapping keys
"""
class SafeDumper(Emitter, Serializer, SafeRepresenter, Resolver):
"""
Safe dumper for standard Python types.
Only represents standard Python types, preventing arbitrary code serialization.
Recommended for general YAML output.
Constructor parameters: (same as BaseDumper)
"""
class Dumper(Emitter, Serializer, Representer, Resolver):
"""
Full-featured dumper with extended Python object support.
Can represent complex Python objects including functions and classes.
Constructor parameters: (same as BaseDumper)
"""import yaml
from io import StringIO
yaml_content = """
name: John Doe
age: 30
skills:
- Python
- YAML
active: true
"""
# Using SafeLoader directly
stream = StringIO(yaml_content)
loader = yaml.SafeLoader(stream)
try:
data = loader.get_single_data()
print(data)
finally:
loader.dispose()
# More convenient - let PyYAML manage the loader
data = yaml.load(yaml_content, Loader=yaml.SafeLoader)
print(data)import yaml
from io import StringIO
data = {
'name': 'John Doe',
'age': 30,
'skills': ['Python', 'YAML'],
'active': True
}
# Using SafeDumper directly
stream = StringIO()
dumper = yaml.SafeDumper(
stream,
default_flow_style=False,
indent=4,
sort_keys=True
)
try:
dumper.open()
dumper.represent(data)
dumper.close()
yaml_output = stream.getvalue()
print(yaml_output)
finally:
dumper.dispose()
# More convenient - let PyYAML manage the dumper
yaml_output = yaml.dump(data, Dumper=yaml.SafeDumper, indent=4, sort_keys=True)
print(yaml_output)import yaml
# Safe YAML that works with all loaders
safe_yaml = """
name: John
numbers: [1, 2, 3]
mapping: {key: value}
"""
# YAML with Python-specific constructs
python_yaml = """
name: John
coordinates: !!python/tuple [10, 20]
dataset: !!set {a, b, c}
"""
# YAML with potentially dangerous constructs
dangerous_yaml = """
name: John
command: !!python/object/apply:subprocess.call [['rm', '-rf', '/']]
"""
# SafeLoader - works with safe YAML only
data1 = yaml.load(safe_yaml, Loader=yaml.SafeLoader) # ✓ Works
try:
data2 = yaml.load(python_yaml, Loader=yaml.SafeLoader) # ✗ Error
except yaml.constructor.ConstructorError as e:
print("SafeLoader rejected Python constructs")
# FullLoader - works with safe YAML and basic Python types
data3 = yaml.load(safe_yaml, Loader=yaml.FullLoader) # ✓ Works
data4 = yaml.load(python_yaml, Loader=yaml.FullLoader) # ✓ Works
try:
data5 = yaml.load(dangerous_yaml, Loader=yaml.FullLoader) # ✗ Error
except yaml.constructor.ConstructorError as e:
print("FullLoader rejected dangerous constructs")
# UnsafeLoader - works with everything (DANGEROUS!)
data6 = yaml.load(safe_yaml, Loader=yaml.UnsafeLoader) # ✓ Works
data7 = yaml.load(python_yaml, Loader=yaml.UnsafeLoader) # ✓ Works
# data8 = yaml.load(dangerous_yaml, Loader=yaml.UnsafeLoader) # ✓ EXECUTES CODE!import yaml
from collections import OrderedDict
import datetime
data = {
'string': 'hello',
'integer': 42,
'float': 3.14,
'boolean': True,
'list': [1, 2, 3],
'dict': {'nested': 'value'},
'tuple': (1, 2, 3),
'set': {1, 2, 3},
'ordered_dict': OrderedDict([('first', 1), ('second', 2)]),
'date': datetime.date(2023, 12, 25),
'datetime': datetime.datetime(2023, 12, 25, 10, 30, 0)
}
# SafeDumper - handles standard types
safe_yaml = yaml.dump(data, Dumper=yaml.SafeDumper)
print("SafeDumper output:")
print(safe_yaml)
# Dumper - handles extended types with custom tags
full_yaml = yaml.dump(data, Dumper=yaml.Dumper)
print("Dumper output:")
print(full_yaml)import yaml
# Complete pipeline: Python -> YAML -> Python
original_data = {
'config': {
'host': 'localhost',
'port': 8080,
'features': ['auth', 'logging', 'metrics']
}
}
# Dump to YAML
yaml_string = yaml.dump(original_data, Dumper=yaml.SafeDumper)
print("YAML output:")
print(yaml_string)
# Load back to Python
restored_data = yaml.load(yaml_string, Loader=yaml.SafeLoader)
print("Restored data:")
print(restored_data)
# Verify round-trip
assert original_data == restored_data
print("Round-trip successful!")Install with Tessl CLI
npx tessl i tessl/pypi-types-pyyaml