StrictYAML

1.7.3 · active · verified Sun Mar 29

StrictYAML is a type-safe YAML parser and validator for Python, focusing on a restricted, unambiguous subset of the YAML specification. It prioritizes a clear API, strict validation, human-readable exceptions, and the ability to round-trip (read, modify, and write) YAML while preserving comments. The current version is 1.7.3, with an active but irregular release cadence of patches and minor versions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to parse a YAML string using a schema for type validation and casting, access parsed data, modify values, and handle potential YAMLError exceptions. It also shows the default behavior of parsing without a schema where all scalar values are treated as strings.

from strictyaml import load, Map, Str, Int, Seq, YAMLError

yaml_snippet = """
name: Ford Prefect
age: 42
possessions:
  - Towel
  - 'No. 2 pencil'
"""

# Define a schema for validation and type casting
schema = Map({"name": Str(), "age": Int(), "possessions": Seq(Str())})

try:
    # Load YAML with the defined schema
    document = load(yaml_snippet, schema)
    print("Parsed data:", document.data)
    print(f"Name (string): {document['name'].data}")
    print(f"Age (int): {document['age'].data}")
    print(f"First possession: {document['possessions'][0].data}")

    # Modify a value and output YAML (comments are preserved)
    document['age'] = 43
    print("\nModified YAML:\n", document.as_yaml())

except YAMLError as e:
    print(f"YAML Error: {e}")

# Example without a schema (all scalars are strings by default)
yaml_no_schema = load(yaml_snippet)
print("\nParsed without schema (age is string):", yaml_no_schema.data['age'])

view raw JSON →