Skip to main content

Cross-platform application configuration manager for Python

Project description

ConfBox

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")

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.1.tar.gz (20.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.1-py3-none-any.whl (9.8 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: confbox-0.1.1.tar.gz
  • Upload date:
  • Size: 20.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.1.tar.gz
Algorithm Hash digest
SHA256 961f6df3a9b8b410357fbab1bde001f0e7232fbbe7321b8412e4fbac7e5cdce2
MD5 605d6644c7c9903a38c612e636ed6a2f
BLAKE2b-256 bde91f78dee668d3feee249da11c75d959b75c41f30e2900bbffb09ffdad2cdf

See more details on using hashes here.

File details

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

File metadata

  • Download URL: confbox-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 9.8 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.1-py3-none-any.whl
Algorithm Hash digest
SHA256 7b4fe4aea6ed4343802233339cb59be50299affa39456b39a4cfde343a75b02c
MD5 664866ff0135e1764e8264e0911569ef
BLAKE2b-256 d202adf4bcf0fd76406e8efd6f11e4dd128f49581552f6c0ca634241adf43770

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