Clevis
Configuration management for Python projects with dataclass-based schemas
Clevis provides type-safe configuration management for Python applications:
- Dataclass schemas — Define config structure with Python dataclasses
- TOML support — Load from
.tomlfiles with automatic discovery - Env vars —
${VAR}interpolation (with envtoml/tomlev extras) - Keyring —
${keyring:service/username}secret interpolation (optional extra) clevisCLI —clevis cat file.tomldumps the fully interpreted config (debug helper);clevis keyring setstores secrets interactively- CLI generation — Auto-generate argparse from dataclass
- Layered config — User config < project config < CLI args
- Subcommands — Build CLI apps with multiple commands
- Dynamic registration — Plugin architecture with runtime field injection
- Security — File permission validation to protect credentials
Quick Start
Get running in 30 seconds:
# Install (Python 3.11+)
pip install clevis
# Or with environment variable support
pip install clevis[envtoml]
# Or with keyring (system keychain) secret support
pip install clevis[keyring]
from dataclasses import dataclass
from clevis import get_config
@dataclass
class Config:
name: str = "MyApp"
debug: bool = False
port: int = 8080
# Load from ~/.myapp.toml, ./myapp.toml, and CLI args
config = get_config(Config, name="myapp")
print(config.name) # Access as attribute
print(config.debug) # Type-safe access
print(config.port) # Automatic type conversion
That's it! Create a myapp.toml file:
name = "Production App"
debug = true
[database]
host = "db.example.com"
port = 5432
Override with CLI:
python app.py --name "Custom App" --port 9000
Features
| Feature | Description | Example |
|---|---|---|
| Dataclass schemas | Type-safe configuration | @dataclass class Config: ... |
| TOML loading | Auto-discover config files | get_config(Config, name="myapp") |
| Environment vars | ${VAR} interpolation |
pip install clevis[envtoml] |
| CLI arguments | Auto-generate argparse | python app.py --database-host localhost |
| Boolean flags | --flag for True, --no-flag for False |
python app.py --debug / --no-debug |
| List append | Repeat --field val |
python app.py --packages pkg --packages c3 |
| Layered config | Defaults < User < Project < CLI | Priority-based merging |
| Nested configs | Hierarchical configuration | [database] host = "localhost" |
| Subcommands | Multi-command CLI apps | @configclass(cmd="build") |
| Default subcommand | Run command when none specified | @configclass(cmd="check", default_cmd=True) |
| Factory pattern | Multi-module orchestration | get_factory(Config).prefix = "app1" |
| Dynamic registration | Plugin architecture | register_field(Parent, "plugin", PluginConfig) |
| Security | File permission validation | SecurityAction.REJECT (default) |
Installation
Choose your TOML parser based on needs:
| Extra | Features | Use When |
|---|---|---|
| (none) | Stdlib tomllib |
Python 3.11+, minimal deps |
tomli |
Pure Python TOML | Python 3.10 compatibility |
envtoml |
${VAR} interpolation |
Environment-based config |
tomlev |
`${VAR | default}` syntax |
[keyring] |
${keyring:service/username} secrets |
Credentials without plaintext configs |
# Python 3.11+ - no extras needed
pip install clevis
# Python 3.10
pip install clevis[tomli]
# Environment variable support
pip install clevis[envtoml]
# System keyring secret support
pip install clevis[keyring]
Core Concepts
Configuration Priority
Values are merged in order (highest priority wins):
- CLI arguments —
--database-host localhost - Environment variables — Only when using envtoml/tomlev
- Project TOML —
./myapp.toml - User TOML —
~/.myapp.toml - Dataclass defaults — Default values in class definition
v0.7.0 breaking change: User and project TOML files now use deep merge (nested dicts combine key-by-key) instead of shallow replacement.
Security
Clevis validates file permissions by default:
from clevis import get_config, SecurityAction
# Default: reject insecure configurations
config = get_config(Config, name="myapp")
# Disable checks (for containers, testing)
config = get_config(
Config,
name="myapp",
security={"file_permissions": SecurityAction.DONT_CHECK}
)
# Log warnings instead of rejecting
config = get_config(
Config,
name="myapp",
security={"file_permissions": SecurityAction.LOG}
)
Custom Config Sources
Inject config from any source (env vars, databases, remote services) by appending a custom provider to the default cascade. Any zero-argument callable returning a dict works — a plain function is the simplest form:
from clevis import build_default_cascade, get_config
def env_provider() -> dict:
import os
return {"api_key": os.environ.get("API_KEY", "")}
cascade = build_default_cascade("myapp") + [env_provider]
config = get_config(Config, name="myapp", cascade=cascade)
Use a class with __call__ when the provider needs constructor parameters.
See docs/usage.rst for the full guide including security helpers for custom providers.
Secrets from the System Keyring
Store credentials in the OS keychain and reference them from TOML — no secrets in plaintext config files:
# myapp.toml
[database]
password = "${keyring:myapp/db-password}"
Store the secret once with the clevis helper command (getpass prompt —
nothing lands in shell history):
pip install clevis[keyring]
clevis keyring set myapp db-password
Password for myapp/db-password: ****
Repeat: ****
To inspect what a TOML file looks like after full Clevis interpretation (keyring + env-var interpolation applied), use:
clevis cat myapp.toml
At load time, Clevis expands the placeholder against the system keyring
before any TOML parser runs. keyring is imported lazily — only when a
${keyring:...} placeholder is actually encountered — so installs that
never use the syntax stay dependency-free (e.g. containers).
- Works with every TOML backend (envtoml, tomlev, tomli, tomllib)
- Splits on the first
/: the username may contain/ - Missing entry or missing
keyringpackage raises a clearKeyringErrorwith fix-it guidance - Caveat: avoid
${in stored secrets (env-aware backends interpolate it)
Example: examples/keyring_secrets.py.
Examples
The examples/ directory contains 11 comprehensive examples:
| Example | Features Demonstrated | Run Command |
|---|---|---|
| main.py | Basic config, CLI args, TOML, security | uv run python main.py --help |
| nested.py | Nested dataclasses, TOML sections | uv run python nested.py --tool-settings-x 10 |
| validation.py | Custom validation, __post_init__ |
uv run python validation.py --server-url "http://localhost" |
| environment.py | ${VAR} interpolation, credentials |
export DB_HOST=localhost && uv run python environment.py |
| keyring_secrets.py | ${keyring:...} secret interpolation |
clevis keyring set clevis-example db-password && uv run python keyring_secrets.py |
| factory.py | Multi-module orchestration, prefixes | uv run python factory.py --app1-name "first" |
| commands.py | CLI subcommands, aliases | uv run python commands.py check --verbose |
| subcommands.py | TOML override with config parameter |
uv run python subcommands.py cli --server-url "https://api.example.com" |
| library_mode.py | Web framework integration, testing | uv run python library_mode.py |
| dynamic.py | Plugin architecture, register_field() |
uv run python dynamic.py --help |
| plugin.py | Practical plugin implementation | uv run python plugin.py --pkgq-timeout 60 |
See examples/README.md for detailed feature matrix and learning path.
Usage Patterns
For detailed usage patterns and API reference, see PACKAGE.md.
Basic Configuration
from dataclasses import dataclass
from clevis import get_config
@dataclass
class Config:
name: str = "MyApp"
debug: bool = False
config = get_config(Config, name="myapp")
CLI Subcommands
from clevis import configclass, get_cmd, get_config
@configclass(cmd="check", help="Run diagnostics", aliases=["c", "chk"])
class CheckConfig:
verbose: bool = False
fix: bool = False
@configclass(cmd="build", help="Build the project")
class BuildConfig:
output: str = "dist"
if __name__ == "__main__":
cmd = get_cmd()
if cmd == "check":
config = get_config(CheckConfig, project=False, user=False)
print(f"Checking with verbose={config.verbose}")
elif cmd == "build":
config = get_config(BuildConfig, project=False, user=False)
print(f"Building to {config.output}")
Default Subcommand
Run a subcommand automatically when none is specified:
from clevis import configclass, get_cmd, get_config
@configclass(cmd="check", default_cmd=True, help="Run diagnostics")
class CheckConfig:
verbose: bool = False
# Called without subcommand → runs "check" automatically
cmd = get_cmd() # "check"
config = get_config(CheckConfig, project=False, user=False)
Dynamic Registration (Plugin Architecture)
from dataclasses import dataclass
from clevis import register_field, get_config
# Parent config (must NOT be frozen)
@dataclass
class ToolsConfig:
list: str = "default"
# Plugin config
@dataclass
class PkgqToolConfig:
enabled: bool = True
timeout: int = 30
# Register plugin field at runtime
register_field(ToolsConfig, "pkgq", PkgqToolConfig)
# Now ToolsConfig has a pkgq field
config = get_config(ToolsConfig, name="tools")
print(config.pkgq.enabled) # True
print(config.pkgq.timeout) # 30
Library Mode
from clevis import get_config
# Library mode - skip CLI parsing
config = get_config(Config, name="myapp", cli=False)
# Testing
def test_my_config():
config = get_config(
TestConfig,
user=False,
project=False,
args=[]
)
assert config.name == "default"
API Reference
For complete API documentation, see PACKAGE.md or docs/api.rst.
Key functions:
get_config(data_class, name, ..., cascade=None)— Load configuration from TOML and CLIconfigclass(cmd=None, help=None, ..., default_cmd=False)— Decorator for configuration classesregister_field(parent_class, field_name, field_type)— Register plugin fieldsget_factory(config_class)— Get Factory for multi-module appsget_cmd()— Get active subcommand namebuild_default_cascade(name)— Build default ConfigProvider cascadedeep_merge(base, overlay)— Recursive dict mergeload(fp)/loads(s)— Public TOML API (raw, no security)load_toml_file(path)— Secure TOML file loaderConfigProvider— Protocol for custom config sourcesUserConfigProvider/ProjectConfigProvider— Built-in providers
Documentation
- Quick Start — This README
- Examples — examples/README.md with feature matrix
- Package Guide — PACKAGE.md comprehensive API and patterns
- API Reference — docs/api.rst or clevis.readthedocs.io
Testing
# Run tests
make test
# Run tests with coverage
make test-cov
# Run quality checks
make check
Contributing
# Clone the repository
git clone https://github.com/christophevg/clevis.git
cd clevis
# Create development environment
make env-dev
# Run tests
make test
# Run quality checks
make check
# Format code
make format
See Makefile for all available targets.
Acknowledgments
Clevis builds on excellent work from the Python community:
- tomllib — Python 3.11+ stdlib
- tomli — Pure Python TOML 1.0
- envtoml — Env var interpolation
- tomlev — Env vars with defaults
- dacite — Dict-to-dataclass conversion
License
MIT
Metadata
Release files for clevis 0.8.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| clevis-0.8.0.tar.gz | 303.2 kB | Without provenance | Details for clevis-0.8.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| clevis-0.8.0-py3-none-any.whl | Python 3 | none | any | Details for clevis-0.8.0-py3-none-any.whl |
Total release size: 344.3 kB
Release files / clevis-0.8.0.tar.gz
| Download URL | clevis-0.8.0.tar.gz |
|---|---|
| Size | 303.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
930f84c85bde33d6904f1bdc481d33ed1e7e29c9a9aa2f6866f231b70c8dda21
|
|
BLAKE2b-256 checksum How to use checksums |
915384dfe577982919dbf09fb9a55c8c68c95675e3a5badc1e3362c6da1943a7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.11.15
|
Release files / clevis-0.8.0-py3-none-any.whl
| Download URL | clevis-0.8.0-py3-none-any.whl |
|---|---|
| Size | 41.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
7a7aaea811ac10b0765895ec6cb4855745d603e438acf696dbeca2a88901f8bb
|
|
BLAKE2b-256 checksum How to use checksums |
01326ed2e1c11aa6066f0a8f10ec20bb7782dd6c7c58da0974a59383952774bf
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.11.15
|
Security for clevis 0.8.0
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.