AnyConfig

raw JSON →
0.15.1 verified Tue Apr 14 auth: no python

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.

pip install anyconfig
error ModuleNotFoundError: No module named 'anyconfig'
cause The 'anyconfig' library is not installed in the Python environment.
fix
Install the 'anyconfig' library using pip: 'pip install anyconfig'.
error ImportError: cannot import name 'load' from 'anyconfig'
cause The function 'load' is not directly available in the 'anyconfig' module.
fix
Use 'import anyconfig' and then call 'anyconfig.load()'.
error TypeError: load() missing 1 required positional argument: 'filepath'
cause The 'load()' function requires a file path argument to specify the configuration file to load.
fix
Provide the file path as an argument: 'anyconfig.load(filepath)'.
error ValueError: Unsupported file format: '.xyz'
cause The 'anyconfig' library does not support the '.xyz' file format.
fix
Use a supported file format such as JSON, YAML, INI, TOML, or XML.
error AttributeError: module 'anyconfig' has no attribute 'merge'
cause The 'merge' function is not a direct attribute of the 'anyconfig' module.
fix
Use 'anyconfig.utils.merge()' to access the merge function.
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.
fix Ensure all necessary backend packages for the formats you intend to use are installed. The official documentation lists the required dependencies for each format. For example, `pip install anyconfig[yaml,toml]`.
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.
fix When calling `anyconfig.load()` or `anyconfig.loads()`, pass `ac_template=True` to enable template rendering. You may also provide a context dictionary via `ac_context` for template variables, e.g., `anyconfig.load(path, ac_template=True, ac_context={'VAR': 'value'})` or `ac_context=os.environ`.
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.
fix Install `ruamel.yaml` (e.g., `pip install 'anyconfig[yaml]' ruamel.yaml`) and ensure it's available. `anyconfig` will prefer `ruamel.yaml` if installed, which offers superior round-trip preservation for YAML, retaining comments and ordering.
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.
fix Specify the desired merge strategy using the `ac_merge` parameter in `anyconfig.load()`. Available strategies include `anyconfig.MS_REPLACE` (later values replace earlier ones), `anyconfig.MS_NO_REPLACE` (earlier values are kept), and `anyconfig.MS_DICTS_AND_LISTS` (recursive merge for both dicts and lists).
pip install anyconfig[yaml,toml,xml,msgpack,configobj,bson,ini,properties]
pip install 'anyconfig[yaml]==0.15.1' 'ruamel.yaml<0.18'

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)