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.
pip install strictyamlVerified import paths — ran on the pinned version, not inferred.
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.
Access the `.data` attribute (e.g., `load(yaml_str, schema).data`) to retrieve the Python dict/list.
Always define a `schema` using `strictyaml` validators (e.g., `Int()`, `Float()`, `Bool()`) if you require typed data beyond strings, lists, and dicts.
Adhere to the StrictYAML subset of YAML. Avoid features like `!!str` explicit tags, `&anchor` references, and compact JSON-like syntax within your YAML files.
Read the content of your YAML file into a string first, then pass that string to `strictyaml.load()`. Example: `with open('config.yaml', 'r') as f: yaml_string = f.read(); doc = load(yaml_string, schema)`.Provide a schema (`strictyaml.load(yaml_str, schema)`) with appropriate validators (`Str()`, `Int()`, `Bool()`, `Datetime()`, etc.) to enable type conversion.
Adjust the YAML content's structure or a specific value's type to conform to the defined schema, or modify the schema to accept the given YAML structure/type.
```python
from strictyaml import load, Map, Str
yaml_string_correct = "user_name: Alice"
schema = Map({"user_name": Str()})
loaded_yaml = load(yaml_string_correct, schema)
# Error case example:
# yaml_string_error = "user_name: {first: Alice, last: Smith}"
# loaded_yaml = load(yaml_string_error, schema) # This would raise the error
```Ensure the key exists in the YAML document and is allowed by the schema. Use `get()` with a default value to handle optional keys safely, or define the key in the schema using `Optional()`.
```python
from strictyaml import load, Map, Str, Int, Optional
yaml_string = "name: Bob\nage: 30"
schema = Map({"name": Str(), "age": Int(), Optional("email"): Str()})
doc = load(yaml_string, schema)
# Correct access:
print(doc["name"].data)
# Accessing an optional key safely:
email_node = doc.get("email")
if email_node:
print(email_node.data)
else:
print("Email not provided.")
# Error case example:
# print(doc["phone"].data) # Assuming 'phone' is not in schema or YAML
```Correct the YAML syntax by ensuring that strings containing special characters are enclosed in single or double quotes, and that indentation and other YAML syntax rules are followed.
```python
from strictyaml import load, Map, Str
# Corrected YAML: quoting a string with a colon
yaml_string_correct = "message: 'This contains a colon: and other stuff'"
schema = Map({"message": Str()})
loaded_yaml = load(yaml_string_correct, schema)
# Error case example (unquoted string with special characters):
# yaml_string_error = "message: This contains a colon: and other stuff"
# loaded_yaml = load(yaml_string_error, schema) # This would raise the error
```Always provide the YAML content as the first argument to the `strictyaml.load()` function.
```python
from strictyaml import load, Map, Str
# Correct usage with yaml_string
yaml_string = "item: Apple"
schema = Map({"item": Str()})
doc = load(yaml_string, schema)
# Error case example:
# doc = load(schema=schema) # This would raise the TypeError
```