Skip to main content

Dictionary-style configuration with path helpers and automatic environment variable handling

Project description

project-conf

PyPI version Python Support License: MIT

Dictionary-style configuration with path helpers and automatic environment variable handling.

A simple, powerful configuration system that behaves like a dictionary but provides convenient path helpers and automatic environment variable integration. Perfect for Python projects that need clean, flexible configuration management.

✨ Features

  • 🗂️ Dictionary Interface: Full dict compatibility - use config['key'], config.get(), config.update(), etc.
  • 📁 Path Helpers: Automatic directory creation with config.data_path(), config.logs_path(), etc.
  • 🌐 Environment Integration: Automatic override from environment variables and .env files
  • 🎯 Type-Safe Conversion: Smart type conversion based on your defaults
  • 🚀 Auto Project Detection: Finds your project root automatically
  • 🔧 Runtime Modification: Change configuration at runtime, visible globally
  • 📦 Zero Dependencies: Pure Python, no external dependencies

🚀 Quick Start

Installation

pip install project-conf

Basic Usage

from project_conf import setup, get_config

# 1. Define your configuration schema with defaults
setup({
    'database_url': 'sqlite:///app.db',
    'debug': False,
    'max_workers': 4,
    'api_key': '',
    'features': ['auth', 'cache']
})

# 2. Use anywhere in your application
config = get_config()

# Dictionary-style access
print(config['database_url'])  # sqlite:///app.db
config['debug'] = True         # Runtime modification
config.update({'timeout': 30}) # Bulk updates

# Path helpers (creates directories automatically)
db_path = config.data_path('app.db')      # /project/data/app.db
log_file = config.logs_path('server.log') # /project/logs/server.log
cache_dir = config.cache_path()           # /project/cache/

📖 Documentation

Environment Variable Override

Configuration values are automatically overridden by environment variables:

# config.py
setup({
    'database_url': 'sqlite:///dev.db',
    'debug': True,
    'max_workers': 2
})
# Environment variables (case-insensitive, converts types)
export DATABASE_URL="postgresql://localhost/prod"
export DEBUG=false
export MAX_WORKERS=8
config = get_config()
print(config['database_url'])  # postgresql://localhost/prod
print(config['debug'])         # False
print(config['max_workers'])   # 8

.env File Support

Create a .env file in your project root:

# .env
DATABASE_URL=postgresql://localhost/myapp
DEBUG=false
MAX_WORKERS=8
API_KEY=secret-key-123
FEATURES=["auth", "admin", "analytics"]

Values are automatically loaded and type-converted based on your defaults.

Path Helpers

Any method ending with _path becomes a path helper:

config = get_config()

# Directory paths (creates directories)
config.data_path()           # /project/data/
config.logs_path()           # /project/logs/
config.uploads_path()        # /project/uploads/
config.my_custom_path()      # /project/my_custom/

# File paths (creates parent directories)
config.data_path('app.db')           # /project/data/app.db
config.logs_path('server.log')       # /project/logs/server.log
config.uploads_path('image.jpg')     # /project/uploads/image.jpg
config.my_custom_path('file.txt')    # /project/my_custom/file.txt

Type Conversion

Environment variables are automatically converted to match your default types:

setup({
    'debug': False,        # bool: 'true'/'false', '1'/'0', 'yes'/'no'
    'workers': 4,          # int: '8' -> 8
    'timeout': 30.0,       # float: '45.5' -> 45.5
    'name': 'app',         # str: kept as string
    'features': ['auth']   # list: '["auth", "admin"]' -> ['auth', 'admin']
})

Project Root Detection

The project root is automatically detected by looking for:

  1. .git directory (most reliable)
  2. pyproject.toml
  3. setup.py
  4. requirements.txt
  5. poetry.lock
  6. Pipfile
  7. package.json
  8. .env

You can also override with PROJECT_ROOT environment variable or pass it directly:

setup(defaults, project_root='/custom/path')

🎯 Real-World Example

# myproject/config.py
from project_conf import setup

# Single source of truth for configuration
DEFAULTS = {
    'database_url': 'sqlite:///myproject.db',
    'redis_url': 'redis://localhost:6379',
    'debug': False,
    'max_workers': 4,
    'timeout': 30.0,
    'api_key': '',
    'log_level': 'INFO',
    'features': {
        'auth': True,
        'admin': False,
        'analytics': True
    }
}

# Initialize configuration
setup(DEFAULTS)
# myproject/database.py
from project_conf import get_config
from . import config  # Import to ensure setup() is called

def create_connection():
    config = get_config()

    # Use as dictionary
    db_url = config['database_url']
    timeout = config.get('timeout', 30)

    # Use path helper for file location
    if 'sqlite' in db_url:
        db_file = config.data_path('myproject.db')
        return f"sqlite://{db_file}"

    return db_url
# myproject/api.py
from project_conf import get_config
from . import config  # Import to ensure setup() is called

def setup_logging():
    config = get_config()

    # Runtime configuration changes
    if not config.get('api_key'):
        config['api_key'] = 'development-key'

    # Path helpers for log files
    log_file = config.logs_path('api.log')

    return setup_logger(
        level=config['log_level'],
        file=log_file
    )
# myproject/__init__.py
# Ensure configuration is initialized when package is imported
from . import config

🧪 Testing

Run the test suite:

# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run with coverage
pytest --cov=project_conf --cov-report=html

🤝 Contributing

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

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🔗 Links

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

project_conf-0.1.1.tar.gz (19.8 kB view details)

Uploaded Source

Built Distribution

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

project_conf-0.1.1-py3-none-any.whl (8.9 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: project_conf-0.1.1.tar.gz
  • Upload date:
  • Size: 19.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.5

File hashes

Hashes for project_conf-0.1.1.tar.gz
Algorithm Hash digest
SHA256 b2b1bc8b1ab1bddbd35c57ddabd295ba9f0e614d5d175bcea999c2e020dd74e8
MD5 da94d3598ccd89943647567a6cc2a61e
BLAKE2b-256 0b000512614388673b76fe6d5f7f8e4a31a8a908e5a7f32654ae0022d71af677

See more details on using hashes here.

File details

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

File metadata

  • Download URL: project_conf-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 8.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.5

File hashes

Hashes for project_conf-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 782ce286e6c21f7578c0153e3648e7d7f74f53cc82baa185526807ef5e58a468
MD5 c7481322ceb39ae147ce24a14a27cfc8
BLAKE2b-256 ffcde06fda9fbcb5927e0a5f44eebd80e7ce515b8257c6c662281a814708d826

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