Serializing YAML with PyYAML: Difference between revisions
Jump to navigation
Jump to search
Line 29: | Line 29: | ||
==Representer== | ==Representer== | ||
A '''representer''' is a function that serializes a class instance to a YAML node representation. The representer gets a <code>Dumper</code> instance as a first argument, and the data object as the second. | A '''representer''' is a function that serializes a class instance to a YAML node representation. The representer gets a <code>Dumper</code> instance as a first argument, and the data object as the second. The function must return the serialized representation of the data object instance, as a s string. | ||
<syntaxhighlight lang='py'> | |||
def my_representer(dumper, data): | |||
</syntaxhighlight> | |||
=Customizing Output= | =Customizing Output= | ||
==Customizing Output with <tt>dump()</tt> Parameters== | ==Customizing Output with <tt>dump()</tt> Parameters== | ||
==Customizing Output with Representers== | ==Customizing Output with Representers== |
Revision as of 23:05, 7 December 2022
Internal
Overview
The process of serialization to YAML is rendering an in-memory data structure as a YAML-formatted string. The simplest sequence of statements that does that is:
import yaml
data = {
'color': 'red',
'size': 10,
'parts': ['top', 'middle', 'bottom']
}
yaml_string = yaml.dump(data)
The YAML-formatted string will be:
color: red
parts:
- top
- middle
- bottom
size: 10
How PyYAML Serialization Works
Representer
A representer is a function that serializes a class instance to a YAML node representation. The representer gets a Dumper
instance as a first argument, and the data object as the second. The function must return the serialized representation of the data object instance, as a s string.
def my_representer(dumper, data):