PyYAML Include

2.2 · active · verified Fri Apr 10

PyYAML Include extends PyYAML with a powerful mechanism to include other YAML files into a current YAML document. It supports local files, as well as remote files via HTTP, S3, SFTP, and more through its integration with `fsspec`. The current stable version is 2.2, with active development and somewhat irregular but consistent releases addressing new features and breaking changes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `pyyaml-include` to include one YAML file (`database.yml`) into another (`config.yml`). It involves creating an instance of `yaml_include.Constructor` and registering it with a `PyYAML` loader (e.g., `yaml.FullLoader`) for a custom `!inc` tag. The example then loads the main configuration, which resolves the included file content.

import yaml
import yaml_include
import os

# Create dummy YAML files for the example
with open("database.yml", "w") as f:
    f.write("host: localhost\nport: 5432\nname: mydb\n")

with open("config.yml", "w") as f:
    f.write("database: !inc database.yml\napp:\n  name: MyApp\n")

# Register the include tag with a YAML Loader
# It is recommended to use FullLoader for most use cases with unknown sources
yaml.add_constructor("!inc", yaml_include.Constructor(), yaml.FullLoader)

# Load the main YAML file
with open('config.yml', 'r') as f:
    data = yaml.full_load(f)

print(data)
# Expected output: {'database': {'host': 'localhost', 'port': 5432, 'name': 'mydb'}, 'app': {'name': 'MyApp'}}

# Clean up dummy files
os.remove("database.yml")
os.remove("config.yml")

view raw JSON →