How do I load (and dump) comments? In the following code, how can I print out the first comment?
import yaml
code = '''# The following key opens a door
key: value
# this is another comment'''
loaded = yaml.load(code)
# CODE HERE: How to print out 'The following key opens a door'?
https://pypi.python.org/pypi/ruamel.yaml is an alternate implementation that specifically covers this use-case
Any chance for this to ever become a reality? I am using pyyaml with ruamel.yaml in tandem for linting purposes, where there is a real need to also real comments. Still, the current development of ruamel makes it a dependency liability.
Probably not unless someone's volunteering to do all the legwork for it. Comments are completely discarded down at the scanner level by both libyaml and pyyaml, so there's a lot of plumbing required across multiple projects to even make comments a "thing", and you'd still probably have to do custom plumbing at parser level to make a "side lookup" or something that you could consult, or serialize them into your output dict using custom logic. I just can't think of a standard way to do it without those intermediate representations.
How is it going, is it already on the road map? I would really like this feature and I don't want to migrate to another library just because of it :c
My previous statement still applies- pyyaml doesn't have any notion of format preservation, since it deserializes to basic Python types by default. Comments are only recognized at the very lowest level of the parser, just enough to discard them from the document stream. IIUC, ruamel was basically rewritten from the ground up to accommodate format preservation and document round-tripping (and it's taken them a few tries to get it right)- that seems unlikely for this project, where backwards compatibility and stability is the primary community expectation.
Even if someone volunteered to do the work- where should the comments get stashed? Comments could theoretically be stored as dynamic instance attributes on the deserialized objects, but most stock Python types disallow addition of instance attributes, so we'd have to redefine or proxy all the base types to support comments, which has backwards-incompatible serialization and type implications for, well, pretty much everything.
The parser changes are the easy part, but I can't think of a straightforward way to expose comments on the output object graph or to make them round-trippable (especially in the face of other structural changes to the intermediate object graph) without basically starting over. If anyone else can, I'm all ears...
not possible yet?
Most helpful comment
Any chance for this to ever become a reality? I am using pyyaml with ruamel.yaml in tandem for linting purposes, where there is a real need to also real comments. Still, the current development of ruamel makes it a dependency liability.