Skip to main content

Cross-platform application configuration manager for Python

Project description

ConfBox

PyPI version

A Python module for managing application configuration files in OS-specific standard directories.

Features

  • Cross-platform: Automatically uses the correct configuration directory for each OS:
    • Linux: ~/.config/<app_name>
    • macOS: ~/Library/Application Support/<app_name>
    • Windows: %LOCALAPPDATA%\Programs\<app_name>
  • YAML-based: Store configuration in human-readable YAML format
  • Simple API: Easy-to-use interface for reading, updating, and storing config
  • Nested config: Support for nested configuration using dot notation
  • Auto-save: Optional automatic saving after each update
  • Type hints: Full type hint support for better IDE integration

Installation

pip install confbox

Or install from source:

git clone https://github.com/jmmirabile/confbox.git
cd confbox
pip install -e .

Quick Start

from confbox import ConfBox

# Initialize configuration for your app
config = ConfBox("myapp")

# Set configuration values
config.set("server.host", "localhost")
config.set("server.port", 8080)
config.set("database.url", "postgresql://localhost/mydb")

# Save configuration
config.save()

# Later, from anywhere in your application:
config = ConfBox("myapp")
host = config.get("server.host")  # "localhost"
port = config.get("server.port")  # 8080

Usage Examples

Basic Configuration Management

from confbox import ConfBox

# Create config (auto-creates directory and file)
config = ConfBox("myapp")

# Set values
config.set("api_key", "secret-key-123")
config.set("debug", True)
config.set("max_retries", 3)

# Save to disk
config.save()

# Get values
api_key = config.get("api_key")
debug = config.get("debug", default=False)

Nested Configuration

# Set nested values using dot notation
config.set("database.host", "localhost")
config.set("database.port", 5432)
config.set("database.credentials.username", "admin")
config.set("database.credentials.password", "secret")

# Get nested values
db_host = config.get("database.host")
db_user = config.get("database.credentials.username")

# Update multiple values at once
config.update({
    "server": {
        "host": "0.0.0.0",
        "port": 8080,
        "workers": 4
    }
})
config.save()

Auto-save Mode

# Enable auto-save to persist changes immediately
config = ConfBox("myapp", auto_save=True)

# Changes are automatically saved
config.set("last_updated", "2025-01-24")  # Automatically saved

Working with Configuration Files

# Use custom config filename
config = ConfBox("myapp", config_filename="settings.yaml")

# Check if config exists
if config.exists():
    print("Config found at:", config.config_path)

# Get all config as dictionary
all_config = config.to_dict()

# Clear all configuration
config.clear()
config.save()

# Delete specific keys
config.delete("old_setting")

Multiple Configuration Files

You can create multiple ConfBox instances for the same app with different config files:

# Main application config
config = ConfBox("myapp")
# → ~/.config/myapp/app-config.yaml

# API configuration
api_config = ConfBox("myapp", config_filename="api.yaml")
# → ~/.config/myapp/api.yaml

# Database configuration
db_config = ConfBox("myapp", config_filename="database.yaml")
# → ~/.config/myapp/database.yaml

# All configs live in the same app directory
# This allows you to separate concerns while keeping configs organized
config.set("app.version", "1.0.0")
api_config.set("endpoint", "https://api.example.com")
db_config.set("host", "localhost")

config.save()
api_config.save()
db_config.save()

Get Configuration Directory

from confbox import get_app_config_dir

# Get the config directory path for your app
config_dir = get_app_config_dir("myapp")
print(f"Config directory: {config_dir}")

# Create custom files in the config directory
log_file = config_dir / "app.log"
cache_dir = config_dir / "cache"

Example: Command-Line Tool

#!/usr/bin/env python3
"""Example CLI tool using confbox."""

from confbox import ConfBox

def main():
    # Config is loaded from standard location regardless of CWD
    config = ConfBox("mytool")

    # First run setup
    if not config.get("initialized"):
        print("First run detected. Setting up configuration...")
        config.set("initialized", True)
        config.set("version", "1.0.0")
        config.set("user.name", input("Enter your name: "))
        config.save()

    # Use configuration
    username = config.get("user.name")
    print(f"Hello, {username}!")

    # Update last run time
    from datetime import datetime
    config.set("last_run", datetime.now().isoformat())
    config.save()

if __name__ == "__main__":
    main()

API Reference

ConfBox

Main class for managing application configuration.

Constructor:

ConfBox(
    app_name: str,
    config_filename: str = "app-config.yaml",
    auto_create: bool = True,
    auto_save: bool = False
)

Methods:

  • load(): Load configuration from file
  • save(): Save configuration to file
  • get(key, default=None): Get a config value (supports dot notation)
  • set(key, value): Set a config value (supports dot notation)
  • delete(key): Delete a config key
  • update(data): Update config with a dictionary
  • to_dict(): Get entire config as dictionary
  • exists(): Check if config file exists
  • clear(): Clear all configuration

get_app_config_dir

Get the OS-specific configuration directory.

get_app_config_dir(app_name: str, create: bool = True) -> Path

Configuration File Location

The configuration file location depends on your operating system:

OS Default Location
Linux ~/.config/<app_name>/app-config.yaml
macOS ~/Library/Application Support/<app_name>/app-config.yaml
Windows %LOCALAPPDATA%\Programs\<app_name>\app-config.yaml

Development

Install development dependencies:

pip install -e ".[dev]"

Run tests:

pytest

Format code:

black confbox

Type checking:

mypy confbox

License

MIT License - see LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

confbox-0.1.3.tar.gz (23.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

confbox-0.1.3-py3-none-any.whl (10.1 kB view details)

Uploaded Python 3

File details

Details for the file confbox-0.1.3.tar.gz.

File metadata

  • Download URL: confbox-0.1.3.tar.gz
  • Upload date:
  • Size: 23.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.12

File hashes

Hashes for confbox-0.1.3.tar.gz
Algorithm Hash digest
SHA256 0608484f94b8d1ce70273abce315c4865f949d50597e304d904fde3884da0a39
MD5 753faf814c878e7de9e059408c0be172
BLAKE2b-256 3a788b0d26279c414711508038b5eb6eec43e4eb79039ebc546c99d97547bc90

See more details on using hashes here.

File details

Details for the file confbox-0.1.3-py3-none-any.whl.

File metadata

  • Download URL: confbox-0.1.3-py3-none-any.whl
  • Upload date:
  • Size: 10.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.12

File hashes

Hashes for confbox-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 e22865cee61f628961716d8a7b44d4f6d681535970ae95c37ee061646ee5fd7c
MD5 7dd7c4b35d91488dbda314cb4e5ab8a6
BLAKE2b-256 a2cfcfcdbdef900a5cd72399f90c98ae3aa88de035a1c9b1240b536541585a33

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page