Menu

#515 Pattern for extracting comments while walking loaded data

open
nobody
None
minor
task
2024-04-26
2024-04-26
No

Hello! I'm investigating using ruamel.yaml to parse YAML config files and extract values for storage in various secret/parameter store services. One of the things I'd like to do is use comments to create descriptions of parameters. I have a very rough prototype but haven't found much documentation for accessing comments in loaded YAML. Would you mind reviewing my rough code and providing feedback?

import ruamel.yaml
yaml = ruamel.yaml.YAML()
comments = []
inp = """\
abc:
  - a     # comment 1
xyz:
  a: 1    # comment 2
  b: 2
  c: 3
  d: 4
  e: 5
  f: 6 # comment 3
"""
data = yaml.load(inp)
for k in data.keys():
    comments.append(data[k].ca.items)

The biggest concern I have is handling more deeply nested YAML documents.

Thanks in advance!
-Matt

Discussion

  • Anthon van der Neut

    First of all:
    - there is no API and I guarantee that things will change (when I finally have some time), so pin the ruamel.yaml version you use, and wrap the access routines so the needed updates can be done in one place)
    - these kind of questions should be on StackOverflow.

    If your comments are in block style after a key-value pair in a mapping ( your comment 2 and 3) or after a sequence element (your comment 1) then you can find them under .ca.items with the mapping key (or the sequence index). You will have to recursively go over your data (and depending on what you want to do with the comment, keep track of where you are in the data structure.

    Post on stackoverflow with what you want to do with the comments afterwards, just gathering them for gathering sake, make little sense to me.

     
  • Matthew Warren

    Matthew Warren - 2024-04-26

    I appreciate you taking the time to answer my oddball question and confirming my assumptions. I have a pattern that's working well now. If you get around to building an API for comments, I'd be more than happy to elaborate on our use case or contribute to its development. For now, we can consider this issue resolved.

    Thanks again,
    -Matt

     

Log in to post a comment.