Skip to content

YAML

The yaml-tstring package provides render_data, render_text, and render_result for YAML templates.

Docker Compose example

A realistic example building Docker Compose service definitions. The builder function returns a Template object — the caller renders at the point of use:

"""Realistic example: Docker Compose service definitions as YAML.

Builder functions return ``Template`` objects.  The caller renders
with ``render_data()`` or ``render_text()`` at the point of use.
"""

from __future__ import annotations

from string.templatelib import Template

from _display import print_walkthrough
from yaml_tstring import render_result


def compose_service_template(
    *,
    service_name: str,
    image: str,
    image_tag: str,
    host_port: int,
    container_port: int,
    env_vars: dict[str, str],
    depends_on: list[str],
    replicas: int,
) -> Template:
    """Return a Docker Compose web service definition as a reusable Template."""
    return t"""\
services:
  {service_name}:
    image: "{image}:{image_tag}"
    ports:
      - "{host_port}:{container_port}"
    environment: {env_vars}
    depends_on: {depends_on}
    deploy:
      replicas: {replicas}
      restart_policy:
        condition: "on-failure"
"""


def main() -> None:
    tmpl = compose_service_template(
        service_name="api",
        image="ghcr.io/myorg/api-server",
        image_tag="v2.3.0",
        host_port=8080,
        container_port=8080,
        env_vars={"LOG_LEVEL": "info", "WORKERS": "4"},
        depends_on=["postgres", "redis"],
        replicas=3,
    )

    result = render_result(tmpl)

    print_walkthrough(
        title="YAML – Docker Compose",
        template=tmpl,
        result=result,
        notes=[
            "compose_service_template() returns a Template, not rendered text.",
            "Quoted fragments build image ref and port mapping strings.",
            "Dict env_vars renders as a YAML mapping.",
            "List depends_on renders as a YAML sequence.",
        ],
    )


if __name__ == "__main__":
    main()

What to notice

  • compose_service_template() returns a Template, not rendered text
  • Quoted fragments build the image ref and port mapping strings
  • dict values render as YAML mappings
  • list values render as YAML sequences

Release manifest example

This example demonstrates YAML-specific features: anchors, aliases, tags, and block scalars:

"""Tutorial example: build a YAML release manifest from a PEP 750 template."""

from __future__ import annotations

from _display import print_walkthrough
from yaml_tstring import render_result


def main() -> None:
    app_name = "checkout"
    environment = "staging"
    defaults_anchor = "base"
    startup_tag = "str"
    replicas = 3

    template = t"""\
defaults: &{defaults_anchor}
  image: "ghcr.io/example/{app_name}:1.2.3"
  replicas: {replicas}
  startup_message: |
    Starting {app_name}
    in {environment}

service:
  defaults_copy: *{defaults_anchor}
  name: "{app_name}-{environment}"
  mode: !{startup_tag} rolling
"""

    result = render_result(template)

    print_walkthrough(
        title="YAML",
        template=template,
        result=result,
        notes=[
            "The anchor name is interpolated once and reused through an alias.",
            "The release name uses quoted-string fragment interpolation.",
            "The startup message uses YAML block-scalar assembly.",
            "The local tag comes from static punctuation plus an interpolated suffix.",
        ],
    )


if __name__ == "__main__":
    main()

What to notice

  • The anchor name is interpolated once and reused through an alias
  • The release name uses quoted-string fragment interpolation
  • The startup message uses YAML block-scalar assembly
  • The local tag comes from static punctuation plus an interpolated suffix

Interpolation contexts

Context Example Description
Whole value key: {val} Any YAML-representable Python value
Map key {key}: value Must be str
String fragment "{name}-{env}" Inserted inside a quoted string
Anchor &{name} Must be str, non-empty, no whitespace
Alias *{name} Must be str, non-empty, no whitespace
Tag !{tag} Must be str, non-empty, no whitespace
Block scalar Literal (\|) or folded (>) with {fragments} Scalar assembly

Supported types

  • str, int, float, bool, None
  • list (rendered as YAML sequences)
  • dict (rendered as YAML mappings)

Warning

Although YAML 1.2.2 Core Schema supports .inf and .nan, this library rejects float("inf") and float("nan") to keep output portable across parsers. Anchor/tag fragments must be non-empty and whitespace-free.

Profile

Profile Description Default
1.2.2 YAML 1.2.2 Yes
from yaml_tstring import render_data

data = render_data(template, profile="1.2.2")