Skip to main content

config-tree-manager

Reusable Python library for typed, YAML-backed application configuration with deterministic precedence layers, compact override persistence, and rich field metadata for GUIs and validation.

Installation

pip install config-tree-manager

Quick Start

1. Define your configuration model

Use standard Python dataclasses. Annotate fields with field_meta() to attach descriptions, constraints, and persistence rules.

from dataclasses import dataclass, field
from config_tree_manager import ConfigManager, field_meta


@dataclass
class LoggingConfig:
    level: str = field_meta(default="INFO", description="Log verbosity level")


@dataclass
class ServerConfig:
    host: str = field_meta(default="localhost", description="Bind address")
    port: int = field_meta(
        default=8080,
        description="TCP port",
        min_value=1,
        max_value=65535,
    )


@dataclass
class AppConfig:
    debug: bool = field_meta(default=False, description="Enable debug mode")
    logging: LoggingConfig = field(default_factory=LoggingConfig)
    server: ServerConfig = field(default_factory=ServerConfig)

2. Create a manager and load configuration

manager: ConfigManager[AppConfig] = ConfigManager(AppConfig, env_prefix="APP")

result = manager.load(
    "config.yaml",
    cli_overrides=["server.port=9090"],   # optional
)

config: AppConfig = result.config
print(config.server.port)   # 9090 (from CLI override)
print(config.logging.level) # "INFO" (default)

load() returns a LoadResult with the typed config, any warnings, and a live metadata index.

3. Access effective values as plain attributes

# Values are plain Python types — no wrapper objects.
assert isinstance(config.server.port, int)
assert config.debug is False

4. Apply runtime overrides (e.g. from a GUI)

manager.set_runtime_override("logging.level", "DEBUG")
# config.logging.level is now "DEBUG" and the metadata index is updated.

manager.clear_runtime_override("logging.level")  # revert
manager.clear_all_runtime_overrides()             # revert all

5. Save compact overrides

Only fields that differ from their defaults are written. Fields reverted to defaults are removed from the file.

config.debug = True
config.server.port = 9090

manager.save("config.yaml", config, backup=True)

Resulting config.yaml:

debug: true
server:
  port: 9090

Export Modes

The save() method supports flexible export modes via two independent boolean flags: full and include_descriptions. This allows you to generate configuration files suited to different use cases.

Compact overrides (default)

Write only fields that differ from their defaults:

manager.save("config.yaml", config)
# or explicitly:
manager.save("config.yaml", config, full=False, include_descriptions=False)

Full export

Write all settings, including defaults:

manager.save("config.yaml", config, full=True)

Useful for generating reference configurations that show all available options.

Export with descriptions

Add field descriptions as YAML comments. Requires that load() has been called first:

# Compact with descriptions
manager.save("config.yaml", config, include_descriptions=True)

# Full with descriptions
manager.save("config.yaml", config, full=True, include_descriptions=True)

Example output with descriptions:

# Enable debug mode
debug: true
logging:
  # Log verbosity level
  level: INFO
server:
  # Bind address
  host: localhost
  # TCP port
  port: 9090

Line wrapping and long values

The max_line_length parameter (default 80) controls wrapping of long descriptions and string values at word boundaries:

manager.save("config.yaml", config, include_descriptions=True, max_line_length=60)

Multi-line descriptions (using \n in the description string) are split and re-wrapped independently:

field_meta(
    default="...",
    description="First line of explanation.\nSecond line continues here."
)

Long string values (exceeding max_line_length) are automatically formatted as YAML block scalars for readability.


Value Precedence

Layers are merged in this order (lower → higher priority):

DEFAULT < FILE < ENV < CLI < RUNTIME
Layer Source
DEFAULT Declared in the dataclass (field_meta)
FILE YAML file passed to load()
ENV Environment variables (APP_LOGGING_LEVEL)
CLI cli_overrides list passed to load()
RUNTIME In-memory via set_runtime_override()

Environment variable naming: {PREFIX}_{SECTION}_{KEY} in upper-snake-case. Example: logging.level with prefix APP → APP_LOGGING_LEVEL.


Validation and Warnings

Fail-fast validation

load() raises ValidationError on the first field that violates its constraints. You can also validate ad-hoc:

manager.validate(config)           # typed config instance
manager.validate({"debug": True})  # or a flat dict

Constraint codes:

Code Trigger
TYPE_MISMATCH Value type does not match declared field type
OUT_OF_RANGE Numeric value outside min_value/max_value
NULL_NOT_ALLOWED None value on a nullable=False field
COERCE_FAIL allow_coerce=True but conversion failed
PARSE_ERROR Malformed YAML or malformed CLI key=value
LOCK_CONFLICT Advisory lock could not be acquired on save

Unknown-key warnings

Keys in the YAML file that are not registered in the schema are ignored with a warning, not silently dropped and not a hard error.

result = manager.load("config.yaml")
for warning in result.warnings:
    print(f"[{warning.code}] {warning.path}: {warning.message}")

Warning code UNKNOWN_KEY is emitted per unknown leaf path. An entire unknown subtree (unknown parent) produces a single warning.


LoadResult

@dataclass
class LoadResult[TConfig]:
    config: TConfig                    # typed config object
    warnings: list[WarningItem]        # non-fatal diagnostics
    metadata_index: dict[str, FieldMeta]  # live metadata, keyed by dot-path

The metadata_index gives you per-field metadata useful for building GUIs:

meta = result.metadata_index["server.port"]
print(meta.effective_value)  # 9090
print(meta.source)           # ValueSource.FILE
print(meta.default_value)    # 8080
print(meta.description)      # "TCP port"

field_meta reference

field_meta(
    default=...,            # scalar default value
    default_factory=...,    # zero-argument callable (mutually exclusive with default)
    description="",         # human-readable label
    min_value=None,         # inclusive lower bound (numeric fields only)
    max_value=None,         # inclusive upper bound (numeric fields only)
    nullable=True,          # whether None is a valid value
    never_persist=False,    # exclude from all file writes (e.g. tokens)
    allow_coerce=False,     # attempt safe coercion from env/CLI strings
)

Advisory file locking

Enable an advisory lock to prevent concurrent saves from silently overwriting each other:

manager = ConfigManager(AppConfig, use_file_lock=True)

When the lock cannot be acquired, LockConflictError is raised. Without locking (default), last-writer-wins semantics apply.


Running the tests

pip install -e ".[dev]"
pytest

Metadata

Release files for config-tree-manager 0.4.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for config-tree-manager 0.4.2
File Size Uploaded Provenance Actions
config_tree_manager-0.4.2.tar.gz 20.8 kB Without provenance Details for config_tree_manager-0.4.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for config-tree-manager 0.4.2
File Interpreter ABI Platform Actions
config_tree_manager-0.4.2-py3-none-any.whl Python 3 none any Details for config_tree_manager-0.4.2-py3-none-any.whl

Total release size: 47.1 kB

Release files / config_tree_manager-0.4.2.tar.gz

Download URL config_tree_manager-0.4.2.tar.gz
Size 20.8 kB
Tags Source
SHA-256 checksum
How to use checksums
20b147f594a742b5eaa95bdd29ef9c4209fdce060e45e4f0e825114c9f77fd19
BLAKE2b-256 checksum
How to use checksums
422e9e27d9cd77fa3a28a3ea73782910accd22edae0b7fabcec21af79d749812
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.13

Release files / config_tree_manager-0.4.2-py3-none-any.whl

Download URL config_tree_manager-0.4.2-py3-none-any.whl
Size 26.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
336ca4ad84cdd0134fd2da556a073b6381e017d92defec60959ca53211c033a7
BLAKE2b-256 checksum
How to use checksums
b07ac6bfacb3293c2b11836a53a6162234835b67c97431f877c22eb1ca133851
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.13

Security for config-tree-manager 0.4.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page