AnyConfig
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
- gotcha AnyConfig dynamically loads backend parsers. If a dependency for a specific format (e.g., `PyYAML` or `toml`) is not installed, that format will silently not be supported, which can lead to unexpected errors if not handled.
- gotcha Template processing (e.g., Jinja2) within configuration files is disabled by default to prevent unintended side effects. If your configuration files use templating features, they will not be rendered unless explicitly enabled.
- gotcha When dumping YAML files, using the default `PyYAML` backend may result in loss of comments, key order, and specific formatting (e.g., block vs. flow style). This is due to `PyYAML`'s limitations in round-trip preservation.
- gotcha When loading multiple configuration files, `anyconfig` employs a default recursive merge strategy (`anyconfig.MS_DICTS`). This might not be the desired behavior if a simple overwrite or a different merge logic is expected.
Install
-
pip install anyconfig -
pip install anyconfig[yaml,toml,xml,msgpack,configobj,bson,ini,properties] -
pip install 'anyconfig[yaml]==0.15.1' 'ruamel.yaml<0.18'
Imports
- anyconfig.load
import anyconfig config = anyconfig.load('config.yaml') - anyconfig.dump
import anyconfig anyconfig.dump(data, 'output.json')
- anyconfig.loads
import anyconfig config = anyconfig.loads('key: value', ac_parser='yaml') - anyconfig.dumps
import anyconfig config_str = anyconfig.dumps({'key': 'value'}, ac_parser='json')
Quickstart
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)