Lightweight self-documenting configuration classes via Python descriptors.
Project description
cfx
Declare configuration fields next to the classes that use them. Each field carries its own default, type checking, and documentation. Compose any set of configs into a larger one, nested or flat, and get serialization, CLI integration, and a self-documenting display for free.
from cfx import Config, Field
class FormatConfig(Config):
"""Output formatting."""
confid = "format"
precision: int = Field(6, "Decimal places")
encoding: str = Field("utf-8", "Output encoding")
class WorkerConfig(Config, components=[FormatConfig]):
"""Worker settings."""
confid = "worker"
threads: int = Field(4, "Worker threads", minval=1)
timeout: float = Field(30.0, "Request timeout in seconds", minval=0.0)
class AppConfig(Config, components=[WorkerConfig]):
"""Application configuration."""
confid = "app"
name: str = Field("myapp", "Application name")
debug: bool = Field(False, "Enable debug output")
cfg = AppConfig()
print(cfg)
AppConfig: Application configuration.
└─ WorkerConfig: Worker settings.
└─ FormatConfig: Output formatting.
Config | Key | Value | Description
-------------+-----------+-------+---------------------------
AppConfig | name | myapp | Application name
AppConfig | debug | False | Enable debug output
WorkerConfig | threads | 4 | Worker threads
WorkerConfig | timeout | 30.0 | Request timeout in seconds
FormatConfig | precision | 6 | Decimal places
FormatConfig | encoding | utf-8 | Output encoding
- Validated fields — typos and bad values raise immediately at the point of assignment, not silently hours later.
- Self-documenting —
print(cfg)renders a tree of the config hierarchy followed by a unified table of all fields, nested included. In Jupyter the same layout renders as HTML automatically via_repr_html_. - Composable — assemble configs from multiple subsystem configs, nested or flat, with serialization, display, and CLI support throughout.
- Views — project a config tree into a custom namespace. Expose a curated subset of fields under new names with
ConfigView, auto-generate prefixed aliases withAliasedView, or enforce that two fields always stay in sync withMirror. - Serializable — round-trip to/from dict, YAML, and TOML with one method call.
- CLI-ready — every config exposes
add_arguments/from_argparsefor argparse andclick_options/from_clickfor Click. Nested sub-configs use dot-notation flags (e.g.--worker.threads). - Extensible — subclass
ConfigFieldto add your own field types with custom validation and normalization. - Zero hard dependencies — YAML, TOML, and Click support are optional.
Installation
pip install cfx
With optional serialization and CLI backends:
pip install "cfx[yaml]" # adds PyYAML
pip install "cfx[toml]" # adds tomli-w
pip install "cfx[click]" # adds Click
pip install "cfx[all]" # everything
Quick start
from cfx import Config, Field
from typing import Literal
class ProcessingConfig(Config):
confid = "processing"
iterations: int = Field(100, "Number of iterations", minval=1)
threshold: float = Field(0.5, "Acceptance threshold", minval=0.0, maxval=1.0)
label: str = Field("run_01", "Human-readable run label")
mode: Literal["fast", "balanced", "thorough"] = Field("fast", "Processing mode")
verbose: bool = Field(False, "Enable verbose logging")
cfg = ProcessingConfig()
# Dot access and dict-style access are interchangeable
cfg.iterations = 200
cfg["mode"] = "thorough"
# Bad values raise immediately
cfg.threshold = 1.5 # ValueError: Expected value <= 1.0, got 1.5
# Serialize to dict, YAML, or TOML
d = cfg.to_dict()
cfg2 = ProcessingConfig.from_dict(d)
# Copy with overrides, diff two instances
modified = cfg.copy(iterations=500)
cfg.diff(modified) # {'iterations': (200, 500)}
For custom field types not expressible via annotations (custom validation,
angular ranges, unit normalization), import explicit types from cfx.types:
from cfx.types import Float, ConfigField
class Angle(ConfigField):
def validate(self, value):
if not isinstance(value, (int, float)):
raise TypeError(f"Expected a number, got {type(value).__name__!r}")
def __set__(self, obj, value):
if self.static:
raise AttributeError("Cannot set a static config field.")
self.validate(value)
setattr(obj, self.private_name, float(value) % 360.0)
Views
Project any config tree into a custom namespace — useful when the internal structure is more complex than what a consumer needs to see:
from cfx import Config, Field, ConfigView, Alias, AliasedView
class ProcessingConfig(Config):
confid = "processing"
iterations: int = Field(100, "Number of iterations")
threshold: float = Field(0.5, "Acceptance threshold")
class FormatConfig(Config):
confid = "format"
precision: int = Field(6, "Decimal places")
encoding: str = Field("utf-8", "Output encoding")
class PipelineConfig(Config, components=[ProcessingConfig, FormatConfig]):
confid = "pipeline"
# Hand-written curated view
class RunSummary(ConfigView):
n_iter = Alias(PipelineConfig.processing.iterations)
decimals = Alias(PipelineConfig.processing.threshold)
cfg = PipelineConfig()
v = RunSummary(cfg)
v.n_iter # 100
v.n_iter = 500
cfg.processing.iterations # 500 — write goes through
# Auto-generated prefixed view (owns its own component instances)
class JobView(AliasedView, components=[ProcessingConfig, FormatConfig]):
pass
jv = JobView()
jv.processing_iterations = 300
jv.format_precision = 3
Environment variables
Back any field with an environment variable — the value is read lazily, so the same class works across environments without subclassing:
from cfx import Config, Field
class ServiceConfig(Config):
host: str = Field("localhost", "Database host", env="DB_HOST")
port: int = Field(5432, "Port", env="DB_PORT")
# DB_HOST=prod.example.com python run.py
cfg = ServiceConfig()
cfg.host # 'prod.example.com' — from env, no code change needed
CLI
Every config exposes add_arguments / from_argparse for argparse and
click_options / from_click for Click. Nested sub-configs use dot-notation
flags automatically:
import argparse
parser = argparse.ArgumentParser()
ProcessingConfig.add_arguments(parser)
cfg = ProcessingConfig.from_argparse(parser.parse_args())
# python run.py --iterations 200 --mode thorough --no-verbose
License
GPL-3.0-only — see LICENSE.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file cfx-0.6.0.tar.gz.
File metadata
- Download URL: cfx-0.6.0.tar.gz
- Upload date:
- Size: 297.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
53087e1699451b94f2cb15f440699e7db23fbec1c905ba11346270ba47718e16
|
|
| MD5 |
3defda105ecb5723c9a3d0fd97cc60d2
|
|
| BLAKE2b-256 |
6e742d097dd1b44e385560c4795a7366449824f8bd346925d30dfce98e98b289
|
Provenance
The following attestation bundles were made for cfx-0.6.0.tar.gz:
Publisher:
publish.yml on DinoBektesevic/cfx
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
cfx-0.6.0.tar.gz -
Subject digest:
53087e1699451b94f2cb15f440699e7db23fbec1c905ba11346270ba47718e16 - Sigstore transparency entry: 1356019965
- Sigstore integration time:
-
Permalink:
DinoBektesevic/cfx@240445687c26fea49dd72d919cf46fb7b3548687 -
Branch / Tag:
refs/tags/v0.6.0 - Owner: https://github.com/DinoBektesevic
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@240445687c26fea49dd72d919cf46fb7b3548687 -
Trigger Event:
push
-
Statement type:
File details
Details for the file cfx-0.6.0-py3-none-any.whl.
File metadata
- Download URL: cfx-0.6.0-py3-none-any.whl
- Upload date:
- Size: 47.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
df5981d8d1aef890af9ec1fac74790fa18638777a2048f4249abe3d43e15a718
|
|
| MD5 |
29be667b623ebe7e9c95dc9659895a9a
|
|
| BLAKE2b-256 |
c87ed56a9f7cc1844e287cfb8b220fab97cbb87dd812cf95ae4ecb607dd90d46
|
Provenance
The following attestation bundles were made for cfx-0.6.0-py3-none-any.whl:
Publisher:
publish.yml on DinoBektesevic/cfx
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
cfx-0.6.0-py3-none-any.whl -
Subject digest:
df5981d8d1aef890af9ec1fac74790fa18638777a2048f4249abe3d43e15a718 - Sigstore transparency entry: 1356019988
- Sigstore integration time:
-
Permalink:
DinoBektesevic/cfx@240445687c26fea49dd72d919cf46fb7b3548687 -
Branch / Tag:
refs/tags/v0.6.0 - Owner: https://github.com/DinoBektesevic
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@240445687c26fea49dd72d919cf46fb7b3548687 -
Trigger Event:
push
-
Statement type: