Skip to main content

A powerful Python configuration management library with support for defaults, CLI args, environment variables, .env files, and optional etcd integration with dynamic updates

Project description

Varlord ⚙️

PyPI version Python 3.7+ License Documentation

Varlord is a powerful Python configuration management library that provides a unified interface for loading configuration from multiple sources with customizable priority ordering and optional dynamic updates via etcd.

✨ Features

  • 🔧 Multiple Sources: Support for defaults, CLI arguments, environment variables, .env files, and optional etcd integration
  • 🎯 Simple Priority: Priority determined by sources order (later overrides earlier)
  • 🔄 Dynamic Updates: Real-time configuration updates via etcd watch (optional)
  • 🛡️ Type Safety: Built-in support for dataclass models with automatic type conversion
  • 📝 Logging Support: Configurable logging to track configuration loading and merging
  • Validation Framework: Built-in validators for range, regex, choice, and custom validation
  • 🔌 Pluggable Architecture: Clean source abstraction for easy extension
  • 📦 Optional Dependencies: Lightweight core with optional extras for dotenv and etcd
  • 🚀 Production Ready: Thread-safe, fail-safe update strategies, and comprehensive error handling
  • 🎨 Simple API: Convenience methods and auto-injection for cleaner code

📦 Installation

Basic Installation

pip install varlord

With Optional Dependencies

# With .env file support
pip install varlord[dotenv]

# With etcd support
pip install varlord[etcd]

# With all optional dependencies
pip install varlord[dotenv,etcd]

# Development installation
pip install -e ".[dev]"

🚀 Quick Start

Basic Usage

from dataclasses import dataclass
from varlord import Config, sources

@dataclass(frozen=True)
class AppConfig:
    host: str = "127.0.0.1"
    port: int = 8000
    debug: bool = False

# Simple way: reorder sources (later sources override earlier ones)
cfg = Config(
    model=AppConfig,
    sources=[
        sources.Defaults(model=AppConfig),  # From model defaults
        sources.Env(prefix="APP_"),        # APP_HOST, APP_PORT, etc.
        sources.CLI(),                     # --host, --port, --debug (model auto-injected)
    ],
)

app = cfg.load()
print(app.host)  # Can be overridden by env var or CLI arg
print(app.port)

Convenience Method

# One-line setup for common cases
cfg = Config.from_model(
    AppConfig,
    env_prefix="APP_",
    cli=True,
    dotenv=".env",
)

app = cfg.load()

Priority Ordering

Method 1: Reorder sources (recommended - simplest)

# Priority is determined by sources order: later sources override earlier ones
cfg = Config(
    model=AppConfig,
    sources=[
        sources.Defaults(model=AppConfig),  # Lowest priority
        sources.Env(prefix="APP_"),
        sources.CLI(),  # Highest priority (last)
    ],
)

Method 2: Use PriorityPolicy (advanced: per-key rules)

from varlord import PriorityPolicy

# Use when you need different priority rules for different keys
cfg = Config(
    model=AppConfig,
    sources=[...],
    policy=PriorityPolicy(
        default=["defaults", "env", "cli"],  # Default order for all keys
        overrides={
            "secrets.*": ["defaults", "etcd"],  # Secrets: skip env, only etcd can override
        }
    ),
)

Dynamic Updates with Etcd

def on_change(new_config, diff):
    print("Config updated:", diff)

cfg = Config(
    model=AppConfig,
    sources=[
        sources.Defaults(model=AppConfig),
        sources.Env(prefix="APP_"),
        sources.Etcd("http://127.0.0.1:2379", prefix="/app/", watch=True),
    ],
)

store = cfg.load_store()  # Automatically enables watch if sources support it
store.subscribe(on_change)

current = store.get()  # Thread-safe access to current config

Logging

Enable debug logging to track configuration loading:

import logging
from varlord import set_log_level

set_log_level(logging.DEBUG)
cfg = Config(...)
app = cfg.load()  # Logs source loads, merges, type conversions

Validation

Add validation in your model's __post_init__:

from varlord.validators import validate_range, validate_regex

@dataclass(frozen=True)
class AppConfig:
    port: int = 8000
    host: str = "127.0.0.1"

    def __post_init__(self):
        validate_range(self.port, min=1, max=65535)
        validate_regex(self.host, r'^\d+\.\d+\.\d+\.\d+$')

📚 Documentation

Full documentation is available at https://varlord.readthedocs.io

🎯 Key Concepts

Configuration Model

Use dataclass to define your configuration structure with type hints and default values.

Sources

Each source implements a unified interface:

  • load() -> Mapping[str, Any]: Load configuration snapshot
  • watch() -> Iterator[ChangeEvent] (optional): Stream of changes for dynamic updates
  • name: Source name for identification

Priority Ordering

Simple (Recommended): Reorder sources list - later sources override earlier ones.

Advanced: Use PriorityPolicy for per-key priority rules (e.g., different rules for secrets).

Type Conversion

Automatic conversion from strings (env vars, CLI) to model field types (int, float, bool, etc.).

Validation

Add validators in your model's __post_init__ method to validate configuration values.

ConfigStore

Runtime configuration management with:

  • Thread-safe atomic snapshots
  • Dynamic updates via watch mechanism
  • Change subscriptions

🤝 Contributing

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

📄 License

Licensed under the Apache License 2.0. See LICENSE for details.

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

varlord-0.1.0.tar.gz (76.2 kB view details)

Uploaded Source

Built Distribution

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

varlord-0.1.0-py3-none-any.whl (36.7 kB view details)

Uploaded Python 3

File details

Details for the file varlord-0.1.0.tar.gz.

File metadata

  • Download URL: varlord-0.1.0.tar.gz
  • Upload date:
  • Size: 76.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.14

File hashes

Hashes for varlord-0.1.0.tar.gz
Algorithm Hash digest
SHA256 f6ac694f37f630b87a50e40530047d24015d2db9d4b0cee92766c3bd15685cef
MD5 1888a957c542567dcd5bfc235ec9db0f
BLAKE2b-256 922a99d1fb507352d425df41f42abe3822eb0ad1caddb9183417af3db3018346

See more details on using hashes here.

File details

Details for the file varlord-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: varlord-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 36.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.14

File hashes

Hashes for varlord-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0f3f6f39cf5763c80e2092d6fa4d8c56d6af6064f850eab3cadce217b0fb59a6
MD5 a7d62e2fff4425e6b0644fe05fc30a75
BLAKE2b-256 795dccbab0aed1efa0dbb88ba80944d512193b89411a06bc9b7b16b8c284122d

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