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.4.tar.gz (23.9 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.4-py3-none-any.whl (10.3 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: confbox-0.1.4.tar.gz
  • Upload date:
  • Size: 23.9 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.4.tar.gz
Algorithm Hash digest
SHA256 12ae97eb35f28c140bb7222d8889b9b5f7e3dc411b73a181e957096e02212bca
MD5 52e81fb31c94e662fea31d7d8703ed10
BLAKE2b-256 e5e06a46d7012d978dd9db7b0856ad1d85ea270cd741eec87880f54ba85163a7

See more details on using hashes here.

File details

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

File metadata

  • Download URL: confbox-0.1.4-py3-none-any.whl
  • Upload date:
  • Size: 10.3 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.4-py3-none-any.whl
Algorithm Hash digest
SHA256 f33d83a1be10e0d7fd876c138d5b143336c27f0fc71e45fd75f7ce6aa0b34e46
MD5 20c589f5bc95dd32927c9dd16d9b1596
BLAKE2b-256 f3cee51b122d84664fd68d46ceb19e68e14a7943625499b7802a99a4cdd0da7d

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