How do I get the sequences properly indented using ruamel.yaml?
With the following data
from ruamel import yaml
data = {1: {1:[{1:1,2:2},{1:1,2:2}], 2:2}, 2: 42}
I am getting wrong indentation for sequence
>>> print yaml.round_trip_dump(data)
1:
1:
- 1: 1
2: 2
- 1: 1
2: 2
2: 2
2: 42
What cannot be folded in Notepad ++. However, with appropriate indentation, it works:
Poorly:
Good:
I tried using block_seq_indent=2
:
>>> print yaml.round_trip_dump(data, block_seq_indent=2)
1:
1:
- 1: 1
2: 2
- 1: 1
2: 2
2: 2
2: 42
How can I solve this problem?
source to share
The documentation ruamel.yaml
, although usually missing, says the following about a offset
dash inside indentation:
If the offset is equal to the sequence, there is not enough room for the dash and the space that must follow it. In this case, the element itself will usually wrap to the next line (and older versions of ruamel.yaml did this). But this is prevented. However, the indentation level is what is used to calculate the cumulative indentation for deeper levels and determine the sequence = 3 accordingly. offset = 2 may give a correct but counter intuitive result.
It's best to always have a sequence > = offset + 2 , but that doesn't apply . Depending on your structure, not following this advice could lead to invalid output .
The default indent
(for both mappings and sequences) is 2 if you do:
import sys from ruamel import yaml data = {1: {1:[{1:1,2:2},{1:1,2:2}], 2:2}, 2: 42} yml = yaml.YAML() yml.indent(mapping=2, sequence=4, offset=2) yml.dump(data, sys.stdout)
You get:
1:
1:
- 1: 1
2: 2
- 1: 1
2: 2
2: 2
2: 42
With the old API you are using in your question, you cannot indent differently for mappings and sequences trivially (you need to subclass the Emitter and in the post of the __init__
base class, set the values). And with older versions of ruamel.yaml this was not possible at all.
This only works with the default bootloader (round-trip, ie typ='rt'
), but works as with regular Python dict
resp. list
(like from YAML(typ='safe').load(....)
) and more constructed subclasses used when doingYAML().load(....)
(this requires: ruamel.yaml> = 0.15.30)
source to share