Skip to content
Search

PyYAML

lastmod 2024-10-11created 2015-10-1412 edits

the home of various YAML implementations for Python.

How to install

$ sudo pip install pyyaml

loads

If you want a function similar to Python's json.loads, use the full_load function.

from yaml import full_load

a = """
data:
  - a
  - b
"""

print(full_load(a))

Enhance list indentation

If a list is printed at the indent of the parent depth, like this:

>>> d = {'a': [1, 2, 3]}
>>> print(yaml.safe_dump(d))
a:
- 1
- 2
- 3

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:

>>> print(yaml.dump(d, Dumper=IndentDumper))
a:
  - 1
  - 2
  - 3

New line between paragraphs

If paragraphs are packed tightly together like this:

a:
  b: []
c:
  d: []

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:

a:
  b: []

c:
  d: []

Troubleshooting

Nested collections misbehave on dump

import yaml
document = """
  a: 1
  b:
    c: 3
    d: 4
"""
print yaml.dump(yaml.load(document))

The output is as follows.

a: 1
b: {c: 3, d: 4}

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.

yaml.dump(yaml.load(document), default_flow_style=False)

See also

Favorite site

author Zer0 sitemap