How to get similarly formatted yaml for "safe" and "round-trip"
Asked Answered
F

1

5

ruamel.yaml formats a simple, but nested dictionary differently depending on if it's using the safe or the round-trip representer.

I can't see why the different repersenters should format such a simple dictionary differently, so I'm wondering how to get the safe representer to look similar to the round-trip one in the following example:

from ruamel.yaml import YAML
import sys

data = {'data': {'interval': 5, 'compression': '3'}, 'player': {'ffmpeg': {'name': 'me'}}}
yaml = YAML(typ='safe')
yaml.dump(data, sys.stdout)

This prints

data: {compression: '3', interval: 5}
player:
  ffmpeg: {name: me}

But

yaml = YAML()
yaml.dump(data, sys.stdout)

prints a much nicer output:

data:
  interval: 5
  compression: '3'
player:
  ffmpeg:
    name: me

How can I get the safe version to print similarity?

Freud answered 2/7, 2020 at 3:37 Comment(0)
C
8

The output of the"safe" mode is what PyYAML, from which ruamel.yaml was orginally derived, gives by default, the "leaf collections" are in flow-style. That is more compact, than the all-block-style output of the default (typ="rt"), which doesn't always increase readability. Especially in low numbers of total items (so the total fits in a window), or when the leaf collections have many items (and they wrap over multiple lines).

So the reason why round-trip defaults to all-block-style is because I agree that it looks nicer. Of course when round-trip is used for its intended purpose, the original style of each collection is preserved.

The difference is caused by the default_flow_style attribute on the YAML() instance set to None for "safe" mode and to False for "rt" mode:

import sys
import ruamel.yaml

data = {'data': {'interval': 5, 'compression': '3'}, 'player': {'ffmpeg': {'name': 'me'}}}


yaml = ruamel.yaml.YAML(typ="safe")
yaml.default_flow_style = False
yaml.dump(data, sys.stdout)

which gives:

data:
  compression: '3'
  interval: 5
player:
  ffmpeg:
    name: me

If you set the attribute to True you'll get output that is completely flow-style.

Calliope answered 2/7, 2020 at 4:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.