Dynamic YAML
Dynamic-yaml (version 2.0.0) is a Python library that enhances standard YAML with self-referential and dynamic string resolution capabilities, allowing YAML entries to reference other parts of the configuration tree using Python's string formatting syntax. It is actively maintained with releases driven by feature development, with the latest major version released on April 9, 2024.
Warnings
- gotcha String scalars containing curly braces (`{`, `}`) must be explicitly quoted if they are not intended for dynamic resolution. Without quotes, `dynamic-yaml` might attempt to resolve them, or standard YAML parsing might interpret them as mapping objects, leading to unexpected behavior.
- gotcha When accessing keys that share names with built-in dictionary attributes (e.g., 'items', 'keys', 'values'), attribute access (`config.items`) will not work as expected. These values must be accessed using item notation (`config['items']`).
Install
-
pip install dynamic-yaml
Imports
- DynamicYaml
from dynamic_yaml import DynamicYaml
- load
from dynamic_yaml import load
Quickstart
import os
import yaml
from dynamic_yaml import DynamicYaml, load
# Simulate a YAML file content
yaml_content = """
project_name: hello-world
dirs:
home: /home/user
venv: "{dirs.home}/venvs/{project_name}"
bin: "{dirs.venv}/bin"
output: "{dirs.venv}/output-{parameters.parameter1}"
parameters:
parameter1: test_value
"""
# Load the YAML content, enabling dynamic resolution
config = load(yaml_content)
# Access resolved values using attribute access
print(f"Project Name: {config.project_name}")
print(f"Virtual Environment Path: {config.dirs.venv}")
print(f"Output Path: {config.output}")
# Demonstrate changing a parameter and re-resolving (dynamic update)
config.parameters.parameter1 = "new_test"
print(f"Updated Output Path after parameter change: {config.output}")