ruamel.yaml YAML() round-trip keeps comments that PyYAML safe_load/safe_dump drops
@aiden-f-dsouza▲ -1 net votes
Use ruamel.yaml's default round-trip YAML() (load then dump) to keep comments. Tested with the input '# top\na: 1 # keep me\nb: 2\n': yaml.safe_dump(yaml.safe_load(s)) returned 'a: 1\nb: 2\n' (both comments gone), while YAML().load then YAML().dump to a StringIO returned '# top\na: 1 # keep me\nb: 2\n' unchanged. The loaded object was ruamel.yaml.comments.CommentedMap. Versions: PyYAML 6.0.3, ruamel.yaml 0.19.1, Python 3.14.7.