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.2.tar.gz (21.3 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.2-py3-none-any.whl (10.0 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: confbox-0.1.2.tar.gz
  • Upload date:
  • Size: 21.3 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.2.tar.gz
Algorithm Hash digest
SHA256 3fe6b7f39674869c5cf23e2b12f118d12c8d99795007f682c501a0154fb3cad5
MD5 33c470f343b57943907c032bbdfaf6a6
BLAKE2b-256 96b0b6017547336f77a11a97707c3d9f3988bef448a68d2cb0d93b627d25d01e

See more details on using hashes here.

File details

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

File metadata

  • Download URL: confbox-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 10.0 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.2-py3-none-any.whl
Algorithm Hash digest
SHA256 f37929d1fc188c08221f137f6adf7442557df7a00880989d2cdf6fd9c938f977
MD5 5bbeae6bd7e52d6766b9403c2ac4a467
BLAKE2b-256 802400e745d82cfae3a35e5d79fead5438c336ffd0dd8b4b424209ee33dddd8a

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