AssertionError on dump with commented, aliased map key and child
ruamel.yaml is a YAML 1.2 parser/emitter for Python
Brought to you by:
anthon
When using an alias as a map key, ruamel.yaml crashes with an assertion upon dumping the document when the parent and child each have a comment (even a blank line).
Sample Document:
---
aliases:
- &key_alias hash
*key_alias :
# A comment
key: value
With ruamel.yaml versions 0.15.96 and 0.16.10 on Pythons 3.6, 3.7, and 3.8, I can parse this YAML document and even change the value. But when I attempt to dump() the document, I get a stack-dump pointing at:
File "env3.6.8/lib/python3.6/site-packages/ruamel/yaml/representer.py", line 1021, in represent_mapping
assert getattr(node_key, 'comment', None) is None
AssertionError
Note that it takes two comments (even if only blank lines) to trigger this assertion error; one before the parent map and one before the child key.
I have requested critical priority because this is happening in the wild and the result is a dump with no document (total loss of data).
I'm guessing this critical bug has been ignored since 2020-06-02 because I didn't provide code to reproduce the error. So, here's the missing code example:
You'll note that the output file is always empty and in this case, the "Done!" message never prints. Please note that my users are typically editing YAML files in-place, so this bug is destructive to user data.
I've already written an error-handler which detects this case and just restores the user's original -- unmodified -- data file in this case, informing them of the extremely unfortunate reason their edit was rejected. However, this issue is still happening in the wild nearly a year later and with newer versions of ruamel.yaml, so when these operations fail, users are frustrated that they cannot affect desired changes to their data files without first deleting or moving their comments.
For ruamel.yaml version 0.17.2, the stack dump shows different line numbers:
This is not trivial to solve correctly. Not throwing an assertion is easy, but the comments after
hash(in this case\n\nget dropped (which is more clear if there are real EOL or full line comments).I am working on redoing the comment handling in 0.17, so I am not going to try and fix this dropping of comments, but I will push out a 0.17.4 that does at least not throw the assertion error.
BTW A working example only helps most if all of the non-relevant parts are excluded. For this a five line python program (excl. YAML source) suffices.