Serializing YAML with PyYAML: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 24: Line 24:
size: 10
size: 10
</syntaxhighlight>
</syntaxhighlight>
=PyYAML Concepts=
PyYAML core model is centered on [[#Constructor|constructors]], [[#Representer|representers]] and [[#Tag|tags]].
==Constructor==
{{External|https://matthewpburruss.com/post/yaml/#defining-pyyaml-constructors-going-from-yaml-to-python}}
A constructor allows you to take a serialized YAML node and return a class instance.
==Representer==
{{External|https://matthewpburruss.com/post/yaml/#defining-pyyaml-representers-going-from-python-to-yaml}}
A representer is a function intercepts data object instances to be serialized, as part of the YAML serialization process, optionally processes them, and then messages the <code>Dumper</code> instance to create the proper serialized representation for the given data object instance, as a <code>Node</code> instance. The instance thus created is returned as result of the function, contributing to the serialization result. The representer gets the <code>Dumper</code> instance as a first argument, and the data object as the second.
<syntaxhighlight lang='py'>
def my_representer(dumper: SafeDumper, data):
  return dumper.represent_scalar()
</syntaxhighlight>
The representers are registered with <code>add_representer()</code>. Representers can be added for specific types (such as <code>str</code> or <code>int</code>), or for ???
<syntaxhighlight lang='py'>
yaml.add_representer(str, my_representer) 
</syntaxhighlight>
==Tag==
The tag uses the special character <code>!</code> preceding the tag name to label a YAML node.
A tag helps PyYAML to know which [[#Constructor|constructor]] or [[#Representer|representer]] to call.


=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:44, 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

Customizing Output

Customizing Output with dump() Parameters

Customizing Output with Representers