1

I have a complex yaml document which gets rendered as

interfaces:
  - name: phy-1_1_1
    description: 'Ansible: cfg phy-1_1_1'
    breakout: to-four
  - name: phy-1_1_2
    description: Interface phy-1_1_2
    admin_status: down
  - name: phy-1_1_3
    description: Interface phy-1_1_3
    admin_status: down
...

The output is not very human friendly when the yaml file grows big.

How can we add an empty linebreak after/before each list blocks i.e. obtain following

interfaces:
  - name: phy-1_1_1
    description: 'Ansible: cfg phy-1_1_1'
    breakout: to-four

  - name: phy-1_1_2
    description: Interface phy-1_1_2
    admin_status: down

  - name: phy-1_1_3
    description: Interface phy-1_1_3
    admin_status: down
...

Inspired from https://github.com/yaml/pyyaml/issues/127 (which addresses a similar problem with toplevel objects), I tried fiddling with yaml dumper class, but could not come up with anything fruitful.

maloy
  • 11
  • 1

1 Answers1

0

cf answers from Formatting PyYAML dump() output.

To summarize, there are 3 options:

  1. Post process the produced yaml and parse it according to your own preferences. This can give something like the following (adapted from the accepted answer of the linked question to use re module instead of plain str.replace):
    import re, yaml
    
    stream = yaml.safe_dump(
        your_data, indent=4, default_flow_style=False, sort_keys=False, width=math.inf
    )
    main_keys = re.compile(r"(\n\w+)")
    next_blocks = re.compile(r"(?<!:)(\n {0,6}- )")  # only first and second level list elements here + exclude the first elements (that directly follow the list's name (and colon) )
    double_newline = lambda m: f"\n{m.group(1)}"  # noqa: E731
    stream, _n = re.subn(main_keys, double_newline, stream)
    stream, _n = re.subn(next_models, double_newline, stream)
    
    with open(your_output_yml_path, "w") as f:
        f.write(stream)
    
  2. Use another (more fruitfully maintained) library for yaml IO. Something like ruamel.yaml suggested as the second most popular option.
  3. Subclass yaml.Dumper like shown on the third answer or on this comment from the pyyaml issue 127.
bluu
  • 542
  • 3
  • 13