ruamel.yaml.string
ruamel.yaml.string is a plugin for the `ruamel.yaml` YAML parser/emitter library. It extends the `ruamel.yaml.YAML` instance by adding `dump_to_string` (and its alias `dumps`) methods, allowing users to serialize YAML documents directly into a Python string instead of writing to a file-like object. The current version is 0.1.1, last updated in May 2023, and its release cadence is tied to `ruamel.yaml` and bug fixes.
Common errors
-
AttributeError: 'YAML' object has no attribute 'dump_to_string'
cause The `ruamel.yaml.YAML` instance was not initialized with `typ=['rt', 'string']` to enable the plugin's methods.fixInitialize your YAML object with `yaml = YAML(typ=['rt', 'string'])`. -
TypeError: dump() takes 2 positional arguments but 3 were given
cause Attempting to pass a `data` object and a stream *and* expecting a string return. The standard `yaml.dump()` method writes to a stream and returns `None`, while `dump_to_string`/`dumps` return a string.fixIf you want a string, use `yaml_string = yaml.dumps(data)`. If you want to dump to a file, use `yaml.dump(data, file_handle)`.
Warnings
- gotcha The `dump_to_string` and `dumps` methods do not add a final newline to the output string by default. This differs from `PyYAML.dump` and `print()` behavior, which often add a newline.
- gotcha For maximum efficiency when dumping YAML, especially for large documents, directly writing to a stream (e.g., `sys.stdout` or a file handle) using `yaml.dump(data, sys.stdout)` is more efficient than first generating a string with `yaml.dumps(data)` and then printing it.
- gotcha The `dump_to_string` and `dumps` methods are only available on a `ruamel.yaml.YAML` instance when initialized with `typ=['rt', 'string']`. If `typ` is not specified or does not include `'string'`, these methods will not be available.
Install
-
pip install ruamel.yaml.string
Imports
- YAML
from ruamel.yaml.string import YAML
from ruamel.yaml import YAML
Quickstart
from ruamel.yaml import YAML
import sys
# Instantiate YAML with the 'string' type to enable dump_to_string/dumps
yaml = YAML(typ=['rt', 'string'])
data = {
'name': 'John Doe',
'age': 30,
'hobbies': ['reading', 'hiking', 'coding'],
'address': {
'street': '123 Main St',
'city': 'Anytown'
}
}
# Dump to string using dump_to_string
yaml_string = yaml.dump_to_string(data)
print('YAML as string (dump_to_string):')
print(yaml_string)
# Dump to string using dumps (alias for dump_to_string)
yaml_string_alias = yaml.dumps(data, add_final_eol=True)
print('\nYAML as string (dumps with final EOL):')
print(yaml_string_alias)