yaml / pyyaml

Canonical source repository for PyYAML
MIT License
2.53k stars 514 forks source link

How can I add blank lines between top-level objects? #127

Open MartinDelVecchio opened 6 years ago

MartinDelVecchio commented 6 years ago

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.

Ujifman commented 6 years ago

I'm interesting too.

Tagman commented 5 years ago

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

yan12125 commented 5 years ago

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
lamnguyenx commented 1 year ago

How to make this work with CSafeDumper, which is much faster than SafeDumper?

derekly-px commented 3 weeks ago

Hi, is this officially merged into pyyaml today? Or does this still need the hack?

Ashark commented 1 week ago

@derekly-px As you can see, this issue is still open...