Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save/dump a YAML file with comments in PyYAML

I have a yaml file that looks like this:

# The following key opens a door key: value 

Is there a way I can load and dump this data while maintaining the comment?

like image 281
Harley Holcombe Avatar asked Aug 31 '11 10:08

Harley Holcombe


People also ask

How do you add a comment in YAML Python?

Inline comments in yaml Here is a code for the yaml inline comments example . It is called single-line comments. Each comment line starts with a hashtag(#) symbol and blank space followed by a description. Each line will end with a new line break.

Is PyYAML same as YAML?

YAML is a data serialization format designed for human readability and interaction with scripting languages. PyYAML is a YAML parser and emitter for the Python programming language.


2 Answers

If you are using block structured YAML, you can use the python package¹ ruamel.yaml which is a derivative of PyYAML and supports round trip preservation of comments:

import sys import ruamel.yaml  yaml_str = """\ # example name:   # details   family: Smith   # very common   given: Alice    # one of the siblings """  yaml = ruamel.yaml.YAML()  # defaults to round-trip if no parameters given code = yaml.load(yaml_str) code['name']['given'] = 'Bob'  yaml.dump(code, sys.stdout) 

with result:

# example name:   # details   family: Smith   # very common   given: Bob      # one of the siblings 

Note that the end-of-line comments are still aligned.

Instead of normal list and dict objects the code consists of wrapped versions² on which the comments attached.

¹ Install with pip install ruamel.yaml. Works on Python 2.6/2.7/3.3+
² ordereddict is used in case of a mapping, to preserve ordering

like image 160
Anthon Avatar answered Sep 18 '22 10:09

Anthon


PyYAML throws away comments at a very low level (in Scanner.scan_to_next_token).

While you could adapt or extend it to handle comments in its whole stack, this would be a major modification. Dumping (=emitting) comments seems to be easier and was discussed in ticket 114 on the old PyYAML bug tracker.

As of 2020, the feature request about adding support for loading comments is still stalling.

like image 44
phihag Avatar answered Sep 19 '22 10:09

phihag