Confuse Configuration Library

2.2.0 · active · verified Sat Apr 11

Confuse is a Python configuration library that simplifies handling YAML-based settings for applications. It provides features like layered overrides, transparent type checking, integration with command-line arguments and environment variables, and automatic discovery of configuration files in OS-specific locations. The current version is 2.2.0, and the project maintains an active release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `confuse.Configuration`, load default settings from a `config_default.yaml` file, and apply overrides from environment variables. It also shows how to retrieve values with type validation using the `.get()` method.

import confuse
import os

# Simulate a config_default.yaml in your package for defaults
# For this example, we'll create a dummy file for demonstration
# In a real app, this would be alongside your module, e.g., myapp/config_default.yaml
with open('config_default.yaml', 'w') as f:
    f.write('greeting: Hello
name: World
port: 8080
enabled: true')

class MyAppConfig(confuse.Configuration):
    # Override config_dir to point to current directory for this example
    # In a real app, this would typically resolve OS-specific paths.
    def config_dir(self):
        return os.getcwd()

# Initialize configuration for 'MyGreatApp'
# __name__ is used by Confuse to find in-package config_default.yaml
config = MyAppConfig('MyGreatApp', __name__)

# Load environment variables with default prefix 'MYGREATAPP_'
# For example, export MYGREATAPP_NAME="Confuse User"
# and MYGREATAPP_PORT=9000
config.set_env()

# Get values, validating types
greeting = config['greeting'].get(str)
name = config['name'].get(str)
port = config['port'].get(int)
is_enabled = config['enabled'].get(bool)

print(f"Greeting: {greeting}")
print(f"Name: {name}")
print(f"Port: {port}")
print(f"Enabled: {is_enabled}")

# Test an environment variable override
os.environ['MYGREATAPP_NAME'] = 'AI Assistant'
os.environ['MYGREATAPP_PORT'] = '9001'

# Reload env vars to pick up changes
config.set_env()

print(f"\nAfter env var override:")
print(f"Name: {config['name'].get(str)}")
print(f"Port: {config['port'].get(int)}")

# Clean up dummy file
os.remove('config_default.yaml')

view raw JSON →