PyYAML
lastmod 2024-10-11created 2015-10-1412 edits
the home of various YAML implementations for Python.
How to install
loads
If you want a function similar to Python's json.loads, use the full_load function.
Enhance list indentation
If a list is printed at the indent of the parent depth, like this:
Override the Dumper as follows:
class IndentDumper(yaml.Dumper):
def increase_indent(self, flow=False, indentless=False):
return super(IndentDumper, self).increase_indent(flow, False)
The list is then printed with an indent:
New line between paragraphs
If paragraphs are packed tightly together like this:
Override the Dumper
class NewLineDumper(Dumper):
def write_line_break(self, data: Optional[str] = None) -> None:
super().write_line_break(data)
if self.indent == ROOT_INDENT:
super().write_line_break(data)
The output becomes:
Troubleshooting
Nested collections misbehave on dump
The output is as follows.
By default, PyYAML chooses the style of a collection depending on whether it has nested collections. If a collection has nested collections, it will be assigned the block style. Otherwise it will have the flow style.
If you want collections to be always serialized in the block style, set the default_flow_style parameter of dump() to False.
See also
Favorite site
- PyYAML web site
- Github - yaml/pyyaml
- PyYAML · PyPI
- (Python) Reading and writing YAML files with PyYAML (Parse and Serialize YAML in Python)