AnyConfig

0.15.1 · active · verified Tue Apr 14

AnyConfig is a Python library that provides a unified API to load and dump configuration files in various formats (e.g., JSON, YAML, INI, TOML, XML). It includes features like content merging, template processing (with Jinja2), data querying (with JMESPath), and JSON schema validation/generation. The current version is 0.15.1, and it maintains a moderate release cadence with several updates per year to introduce new features and address issues.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load a YAML configuration file using `anyconfig.load()`. It highlights automatic format detection by file extension and the use of Jinja2 templating to resolve environment variables within the configuration. It also shows how to dump the loaded configuration to a different format like JSON.

import anyconfig
import os

# Create a dummy YAML config file for demonstration
config_content = """
app:
  name: MyWebApp
  version: 1.0.0
database:
  host: localhost
  port: 5432
  user: dbuser
  password: ${DB_PASSWORD|default_secret}
"""

config_file_path = "./app_config.yaml"
with open(config_file_path, "w") as f:
    f.write(config_content)

# Set an environment variable for template processing (optional)
os.environ['DB_PASSWORD'] = 'supersecurepassword'

# Load the configuration, enabling template processing
config = anyconfig.load(config_file_path, ac_template=True, ac_context=os.environ)

print(f"Application Name: {config['app']['name']}")
print(f"Database Host: {config['database']['host']}")
print(f"Database Password: {config['database']['password']}")

# Example of dumping to another format (e.g., JSON)
output_json_path = "./app_config.json"
anyconfig.dump(config, output_json_path, ac_parser='json', indent=2)
print(f"Configuration dumped to {output_json_path}")

# Clean up dummy files
os.remove(config_file_path)
os.remove(output_json_path)

view raw JSON →