Search code examples
getyamlcommentsruamel.yaml

Issue in getting the comments from YAML using ruamel.yaml


Code:


import ruamel.yaml

yaml_str = """\
# comments start
a: 52
# comment for a
b: 50
# comment for b
c: 50
# comment for c
d:
   # comment for d
   e: 60
   # comment for e
   f: 70
   # comment for f
"""

yaml = ruamel.yaml.YAML()
data = yaml.load(yaml_str)
print(data.ca.comment)
print(data.ca.items)

Output:


[None, [CommentToken('# comments start\n', line: 0, col: 0)]]
{'a': [None, None, CommentToken('\n# comment for a\n', line: 2, col: 0), None], 'b': [None, None, CommentToken('\n# comment for b\n', line: 4, col: 0), None], 'c': [None, None, CommentToken('\n# comment for c\n', line: 6, col: 0), None], 'd': [None, None, None, [CommentToken('# comment for d\n', line: 8, col: 4)]]}

Question:

  1. Why isn't it showing comments pertaining to the keys e and f?
  2. What is the correct way to retrieve the comments based on the key say for example. How to get the comments for the key e ( # comment for e) ?

Solution

  • In ruamel.yaml most comments are attached to the dict (or list) like structure containing the key (or element) after which the comment occurred.

    To get to the comments following keys e and f you need to look at the dict that is the value for d:

    print(data['d'].ca.items)
    print('comment post commment for "e":', repr(data['d'].ca.get('e', 2).value))
    

    which gives:

    {'e': [None, None, CommentToken('\n   # comment for e\n', line: 10, col: 3), None], 'f': [None, None, CommentToken('\n   # comment for f\n', line: 12, col: 3), None]}
    comment post commment for "e": '\n   # comment for e\n'
    

    Please note that the comment for e starts with a newline, indicating there is no end-of-line comment