Donfig
Donfig is a Python library designed to simplify package and script configuration, drawing inspiration from the configuration logic originally found in the Dask library. It allows configuration through programmatic settings, environment variables, and YAML files located in standard paths. The library is actively maintained, with the current version being 0.8.1.post1, and releases occurring periodically to add features and fix bugs.
Warnings
- breaking The `update_defaults` method in `Config` objects changed behavior in v0.8.0. Previously, it might not have consistently overridden existing default values. As of v0.8.0, `update_defaults` will reliably override old default values, which might change behavior if your code relied on the previous 'buggy' non-overriding behavior.
- gotcha When loading configuration from environment variables, Donfig uses `ast.literal_eval` to parse values. This means that environment variable values are interpreted as Python literals (e.g., 'True' becomes `True` boolean, '123' becomes `123` integer, '[1, 2]' becomes a list). This can lead to unexpected type conversions if not accounted for.
- gotcha When setting configuration values using `config.set()`, underscores (`_`) and hyphens (`-`) in key names are treated as identical. For example, `config.set({'my-key': True})` is equivalent to `config.set({'my_key': True})`.
- deprecated Version 0.8.0 introduced support for key deprecation. While not a direct breaking change for existing configurations, this means that future releases of packages using donfig might mark certain configuration keys as deprecated. It's advisable to check documentation for specific applications using donfig to see if any keys you rely on have been deprecated.
Install
-
pip install donfig
Imports
- Config
from donfig import Config
Quickstart
import os
from donfig import Config
# Simulate environment variable for demonstration
os.environ['MYAPP_SETTING_ONE'] = 'env_value'
# Create a configuration object for your application/package
# The name ('myapp' here) is used for environment variable prefixing (e.g., MYAPP_)
# and YAML file searching (e.g., ~/.config/myapp/)
config = Config('myapp', defaults={'setting_one': 'default_value', 'setting_two': 123})
# Access configuration values
value_one = config.get('setting_one')
value_two = config.get('setting_two')
print(f"Setting One (from env): {value_one}")
print(f"Setting Two (from default): {value_two}")
# Update configuration programmatically
config.set(setting_two=456)
print(f"Setting Two (updated): {config.get('setting_two')}")
# Use as a context manager to temporarily change configuration
with config.set(setting_one='context_value'):
print(f"Setting One (in context): {config.get('setting_one')}")
print(f"Setting One (after context): {config.get('setting_one')}")
# Clean up environment variable (optional, for isolated testing)
del os.environ['MYAPP_SETTING_ONE']