YAML Config
Python client for reading YAML based config files. It provides a `Config` class for retrieving configuration variables from YAML files. It allows configuration of root and directory paths via environment variables. The library is currently at version 0.1.5 and has a low-cadence release cycle, with the last PyPI release in June 2020.
Warnings
- breaking Older versions of `yaml-config` (prior to 0.1.3) might have used `PyYAML`'s `yaml.load()` function without explicitly specifying a `Loader` parameter. This usage is considered unsafe and was deprecated in `PyYAML` 5.1+, leading to a `TypeError` in `PyYAML` 6.0+.
- gotcha The `yaml-config` library supports configuring root and directory paths for config files using environment variables (e.g., `<prefix>_CONFIG_ROOT`, `<prefix>_CONFIG_DIR`). However, it does not natively provide functionality for interpolating environment variables *within* the YAML file content itself (e.g., `api_key: ${API_KEY}`).
- gotcha Using `yaml.load()` directly from `PyYAML` without specifying a safe loader (like `yaml.SafeLoader` or `yaml.FullLoader`) is a known security vulnerability, as it can execute arbitrary Python code. Although `yaml-config` versions 0.1.3+ default to `yaml.SafeLoader` for its internal loading, direct interactions with `PyYAML` in your own code should always prioritize safety.
Install
-
pip install yaml-config
Imports
- Config
from yaml_config import Config
Quickstart
import os
from yaml_config import Config
# Create a dummy config file for the example
config_content = """
database:
host: localhost
port: 5432
logging:
level: INFO
"""
with open("my_app_config.yaml", "w") as f:
f.write(config_content)
# You can optionally set environment variables to define config root/dir
# For example, in your shell: export MYAPP_CONFIG_ROOT=/tmp
# This example assumes the file is in the current working directory.
class MyAppConfig(Config):
# Define the default config file name to be loaded
default_file = 'my_app_config.yaml'
# If using environment variables for root/dir, define a prefix:
# default_env_prefix = 'MYAPP' # Would look for MYAPP_CONFIG_ROOT / MYAPP_CONFIG_DIR
# Load the configuration
config = MyAppConfig()
# Access configuration values
print(f"Database Host: {config.database.host}")
print(f"Database Port: {config.database.port}")
print(f"Logging Level: {config.logging.level}")
# Clean up dummy config file
os.remove("my_app_config.yaml")