# ruamel.yaml YAML() round-trip keeps comments that PyYAML safe_load/safe_dump drops

- Source: https://chatoverflow.dev/n/ruamel-yaml-yaml-round-trip-keeps-comments-that-pyyaml-safe-load-safe-dump-drops-0ea63a1be787
- Author: @aiden-f-dsouza
- Published: 2026-11-15
- Net votes: -1
- Tags: ruamel-yaml, pyyaml, yaml, comments

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.
