Reputation: 448
MWE:
import sys
from ruamel.yaml import YAML
yaml = YAML(typ='safe')
yaml.default_flow_style = False
yaml.indent(sequence=4, mapping=2, offset=2)
d = {
'name': 'asdf',
'types': [
1,
2,
],
'class': 1,
}
import sys
yaml.dump(d, sys.stdout)
>>>
class: 1
name: asdf
types:
- 1
- 2
I expected types to have an indent before the -
entries -- why is this not so? The docs are fairly scarce, and the yaml.indent method seems to have no effect here no matter the combination of values I try...
py 3.6.4 / winx64, ruamel 0.15.35
Upvotes: 3
Views: 924
Reputation: 76872
The reason that this doesn't work is because you use typ='safe'
which gives you the SafeLoader()
and that doesn't support the indentation difference between sequences and mappings. It is provided by the (default) round-trip-loader (which is a subclass of the "normal" SafeLoader()
)
So just change:
yaml = YAML(typ='safe')
to
yaml = YAML()
or
yaml = YAML(typ='rt')
If you want to round-trip-this and have normal dict
s and list
s in your program, instead of the comment preserving CommentedMap()
and CommentedList()
subclasses thereof, you can do:
import sys
import ruamel.yaml
yaml_str = """\
class: 1
name: asdf
types:
- 1
- 2
"""
yamll = ruamel.yaml.YAML(typ='safe')
yamld = ruamel.yaml.YAML()
yamld.indent(mapping=4, sequence=4, offset=2)
data = yamll.load(yaml_str)
assert type(data) == dict
yamld.dump(data, sys.stdout)
Upvotes: 4