[Python] Prevent ruamel.yaml from touching unchanged lines when round-trip dumping YAML

Discussão em 'Python' iniciado por Stack, Julho 21, 2025.

  1. Stack

    Stack Membro Participativo

    I’m automating small edits to YAML files (and opening PRs), but I need only the lines I intentionally changed to appear in the diff—yet ruamel.yaml still rewrites lines I never touched. For example, whitespace around colons, blank-line indentation, flow-sequence commas, comments and other punctuation get normalized even though my code only mutates a single key.

    Here’s a minimal example of my workflow:

    from ruamel.yaml import YAML

    yaml = YAML(typ='rt')
    yaml.preserve_quotes = True # keeps single-quoted scalars unchanged
    yaml.width = 4096 # disables automatic line-wrapping

    # 1) Load original YAML
    with open('config.yml') as f:
    data = yaml.load(f)

    # 2) Mutate just one field
    data['policy']['enabled'] = True

    # 3) Overwrite the same file
    with open('config.yml', 'w') as f:
    yaml.dump(data, f)


    preserve_quotes and width helped me in some cases like long lines that were folded and single quotes that were changed, but there are still a lot of unwanted remaining changes:

    • Colon-spacing normalized

    name : prepaid_underbill_corrections

    changed to:

    name: prepaid_underbill_corrections

    • Flow-sequence spacing inserted

    ["a","b","c"]

    changed to:

    ["a", "b", "c"]


    • Blank lines with indentations - indentations are removed


    • Other cosmetic tweaks on untouched lines (comments, trailing spaces, etc.)

    My goal: Only rewrite the YAML lines corresponding to the keys/values I actually changed, and leave every other line, including the spaces around punctuation, blank-line indentation, flow-sequence commas, comments, and anchors completely untouched.

    Questions:


    1. Is there a built-in ruamel.yaml configuration (loader/dumper flags, representer hooks, etc.) that disables all remaining punctuation or whitespace normalization on untouched nodes?


    2. If not, what’s the most elegant, “library-supported” pattern to achieve truly zero-collateral edits? For example, diff-and-patch, custom emitter hooks, or another approach in the round-trip API I may have missed?

      Any pointers or code examples to help me produce PRs that contain only my intended changes would be hugely appreciated!

    Continue reading...

Compartilhe esta Página