Pyyaml: How can I add blank lines between top-level objects?

Created on 2 Feb 2018  路  3Comments  路  Source: yaml/pyyaml

I am using PyYAML to create a Swagger document, which we will share with customers. When I dump it, there are no blank lines between the top-level items:

swagger: '2.0'
host: api.petstore.com
basePath: /api/v1
schemas:
- https
consumes:
- application/json

I would prefer it to have blank lines between these items, e.g.:

swagger: '2.0'

host: api.petstore.com

basePath: /api/v1

schemas:
- https

consumes:
- application/json

Is this possible?

Thanks.

Most helpful comment

Here is an example inspired by https://stackoverflow.com/a/44284819/3786245:

import yaml

data = yaml.safe_load('''
swagger: '2.0'
host: api.petstore.com
basePath: /api/v1
schemas:
- https
consumes:
- application/json
''')


class MyDumper(yaml.SafeDumper):
    # HACK: insert blank lines between top-level objects
    # inspired by https://stackoverflow.com/a/44284819/3786245
    def write_line_break(self, data=None):
        super().write_line_break(data)

        if len(self.indents) == 1:
            super().write_line_break()


print(yaml.dump(data, Dumper=MyDumper, sort_keys=False))

The output is:

swagger: '2.0'

host: api.petstore.com

basePath: /api/v1

schemas:
- https

consumes:
- application/json

All 3 comments

I'm interesting too.

Bump. Is there any option that can be activated to achieve this?

Here is an example inspired by https://stackoverflow.com/a/44284819/3786245:

import yaml

data = yaml.safe_load('''
swagger: '2.0'
host: api.petstore.com
basePath: /api/v1
schemas:
- https
consumes:
- application/json
''')


class MyDumper(yaml.SafeDumper):
    # HACK: insert blank lines between top-level objects
    # inspired by https://stackoverflow.com/a/44284819/3786245
    def write_line_break(self, data=None):
        super().write_line_break(data)

        if len(self.indents) == 1:
            super().write_line_break()


print(yaml.dump(data, Dumper=MyDumper, sort_keys=False))

The output is:

swagger: '2.0'

host: api.petstore.com

basePath: /api/v1

schemas:
- https

consumes:
- application/json

Was this page helpful?
0 / 5 - 0 ratings