YAML in Python: Difference between revisions
Jump to navigation
Jump to search
Line 48: | Line 48: | ||
<syntaxhighlight lang='py'> | <syntaxhighlight lang='py'> | ||
def | def representer_for_none(self, _): | ||
return self.represent_scalar('tag:yaml.org,2002:null', '') | return self.represent_scalar('tag:yaml.org,2002:null', '') | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Line 55: | Line 55: | ||
<syntaxhighlight lang='py'> | <syntaxhighlight lang='py'> | ||
import yaml | |||
[...] | |||
yaml.add_representer(type(None), represent_none) | |||
</syntaxhighlight> | |||
This will render: | |||
<syntaxhighlight lang='py'> | |||
d = { | |||
'a': None, | |||
'b': 'c' | |||
} | |||
</syntaxhighlight> | |||
as: | |||
<syntaxhighlight lang='yaml'> | |||
a: | |||
b: c | |||
</syntaxhighlight> | </syntaxhighlight> | ||
<font color=darkkhaki>what is the lifecycle of the method registered to the module?</font> | <font color=darkkhaki>what is the lifecycle of the method registered to the module?</font> |
Revision as of 20:34, 3 August 2022
Internal
PyYAML
PyYAML provides YAML serialization/deserialization in Python.
Installation
pip install pyyaml
requirements.txt
:
pyyaml == 5.3.1
To install, see the "Installation" section from https://pyyaml.org/wiki/PyYAMLDocumentation.
Overview
Deserialize YAML
import yaml
with open('some-file.yaml', 'rt') as f:
content = f.read()
data = yaml.load(content, Loader=yaml.Loader)
Serialize YAML
import yaml
# with the default flow style, the document is rendered in a non-indented manner
print (yaml.dump(data, default_flow_style=False))
Suggestions on how to safely recursively navigate a complex data structure:
Configure yaml.dump() to render blank instead of null
PyYAML dump()
uses Representer()
to represent None
. By default, the representer dump()
is configured with represents None
as "null". To change that:
1. Define a method that "represents" None
def representer_for_none(self, _):
return self.represent_scalar('tag:yaml.org,2002:null', '')
2. Add it to the module:
import yaml
[...]
yaml.add_representer(type(None), represent_none)
This will render:
d = {
'a': None,
'b': 'c'
}
as:
a:
b: c
what is the lifecycle of the method registered to the module?