I am working with the ruamel.yaml package and I can't seem to get it to output in a nicely formatted flow style. I'd like to keep elements on the same level separated by trailing commas and newlines. I also would like to preserve every comment, and it seems that some disappear after converting to flow style. Here is an example:
Original
background_opacity: 0.9 # comment
cursor: {style: Beam}
# comment
font:
normal: {family: Fira Code, style: Retina} # comment
size: 12.0 # comment
Intended
{
background_opacity: 0.9, # comment
cursor: {style: Beam},
# comment
font: {
normal: {family: Fira Code, style: Retina}, # comment
size: 12.0 # comment
}
}
Actual
{background_opacity: 0.9 # comment
, cursor: {style: Beam}, font: {normal: {family: Fira Code, style: Retina} # comment
, size: 12.0 # comment
}}
My code is attached below. I am pretty new to YAML and ruamel.yaml so I apologize for any simple mistakes.
from ruamel.yaml import YAML
def round_trip(sout, sin, idt):
yaml = YAML()
assert idt >= 2
yaml.indent(mapping=idt, sequence=idt, offset=idt-2)
yaml.preserve_quotes = True
data = yaml.load(sin)
if data is not None:
data.fa.set_flow_style() # needs fixing: commas are not trailing
yaml.dump(data, sout)
else:
print("the file is empty") # needs fixing: should dump original file