PythonizeYAML
Tutorial
API
GitHub
  • English
  • 简体中文
Tutorial
API
GitHub
  • English
  • 简体中文
  • Tutorial

    • Tutorial
    • Loading and dumping
    • Editing values
    • Command line
    • Comments, styles, tags, and anchors
    • Loading untrusted YAML
  • Worked examples

    • Edit a service configuration
    • Build a release metadata command

Build a release metadata command

This example updates a release file used by a small Python project. The loaded Document is enough for value changes; the same object also exposes style editing, which the command uses for comments, quotes, and collection style.

1. Start with a release file

Create release.yaml:

# Published by release.py.
version: '0.3.0'
channel: stable
artifacts:
  - pythonizeyaml
  - pythonizeyaml-docs

2. Load the document and update its metadata

Create release.py:

from pathlib import Path

from pythonizeyaml import ScalarStyle, load_document


def publish(version: str) -> None:
    path = Path("release.yaml")
    document = load_document(path.read_text(encoding="utf-8"))

    document["version"].set(
        value=version,
        style=ScalarStyle.SINGLE,
        inline="# Release version",
    )
    document["channel"].comments.before = ["# Published channel"]
    path.write_text(document.dump(), encoding="utf-8")


if __name__ == "__main__":
    publish("0.4.0")

set() validates all requested style fields before applying the change. If a later field is invalid, the document is restored to its previous state.

3. Verify the result

Running python release.py produces:

# Published by release.py.
# Published channel
version: '0.4.0'  # Release version
channel: stable
artifacts:
  - pythonizeyaml
  - pythonizeyaml-docs

The original quote style is retained and the new comment is attached to the specific node. document.source remains the original source text; use document.dump() for the current representation.

4. Add a new field with style metadata

Assign the value like a plain dict — the assigned value is wrapped, so it can be styled immediately:

document["build"]["command"] = "python -m build"
document["build"]["command"].set(
    style=ScalarStyle.DOUBLE,
    before="# Command used by CI",
)

Use document["artifacts"].collection_style = "flow" when a collection should be emitted as [pythonizeyaml, pythonizeyaml-docs].

Last Updated: 10/3/26, 3:52 PM
Contributors: originalFactor
Prev
Edit a service configuration