Here is the odd thing about configuration bugs: hardly any of them are about the value. They are about authorship. By the time a setting reaches your program it has passed through as many as six hands - the defaults you shipped, a file in /etc, a per-host tweak, something in the user's home directory, a .env, and an environment variable a colleague exported months ago and forgot - and any hand along the way may have changed it. The number you finally read is the last whisper in a long game of telephone, and the library you read it with took no notes. So when the value is wrong, you are not debugging code. You are interviewing witnesses.
The sensible-looking shortcuts are exactly the ones that turn on you:
Read os.environ.get("TIMEOUT", 30) in one module and a config.toml in another, and the real timeout is settled by whichever line ran first. Nobody wins the argument; nobody is even told there was one.
Hard-code /etc/myapp/ because that is plainly where config lives - on Linux. On the macOS and Windows machines that make up most of your users, it lives somewhere else entirely.
Trust "false" from a file as a boolean; a non-empty string is truthy, so you have just shipped with the safety switched off.
Let a password rest in the config file, let the config file drift into git, and you have handed a secret a permanent home address.
Assign to the shared settings dict from three call-frames deep, and "the configuration" now means different things depending on what ran when.
None of these are hard to fix once. They are hard to fix forever, because the single fact you need the moment it breaks - who set this value, and from where - was thrown away at the door.
Configuration, with a paper trail
lib_layered_config begins with the part every other approach discards: the paperwork. It deep-merges the six layers - defaults -> app -> host -> user -> dotenv -> env - into one immutable object, in a precedence that never shifts, and it keeps the receipt. Ask for a value and it answers; ask where the value came from and it names the exact layer and file. The witness interview collapses into a lookup.
What that buys you:
One frozen object.read_config(...) returns a Config nothing downstream can mutate, so your program cannot quietly begin to disagree with itself. A nested table or list you read comes back as your own copy, and the Config itself supports copy.deepcopy and pickle, so it can be cloned or sent to another process.
Every value carries its origin.config.origin("service.timeout") reports the layer and the path it came from. Debugging stops being a seance.
The paths are already sorted. Linux (XDG), macOS, and Windows locations are resolved for you, so you never bake someone else's /etc into your code.
One name switches the whole environment. Profiles keep test, staging, and production in separate trees; ask for profile="production" and you get production's config, not a hand-merged guess at it.
Secrets sit above the file, not inside it. Environment variables and .env outrank the committed config, which therefore holds shape rather than passwords - and the CLI masks them on the way out unless asked not to (--no-redact).
Same engine from either side: from lib_layered_config import read_config as a library, or a lib_layered_config command that reads, deploys, and scaffolds configuration without a line of Python.
In one sentence: a cross-platform configuration loader that deep-merges application defaults, host overrides, user profiles, .env files, and environment variables into a single immutable object. The core follows Clean Architecture boundaries so adapters (filesystem, dotenv, environment) stay isolated from the domain model while the CLI mirrors the same orchestration.
Deterministic layering - precedence is always defaults → app → host → user → dotenv → env.
Immutable value object - returned Config prevents accidental mutation, down to nested tables and lists, supports copy.deepcopy and pickle, and exposes dotted-path helpers.
Provenance tracking - every key reports the layer and path that produced it.
Cross-platform path discovery - Linux (XDG), macOS, and Windows layouts with environment overrides for tests.
Configuration profiles - test, staging, and production live in separate trees; select one by name (profile="production") instead of hand-merging environments.
.d directory support - split configuration into multiple files using the Linux .d pattern (e.g., config.d/10-database.toml). Supports mixed formats (TOML, YAML, JSON) in the same directory.
Easy deployment - deploy configs to app, host, and user layers with smart conflict handling that protects user customizations through automatic backups (.bak) and UCF files (.ucf) for safe CI/CD updates.
Fast parsing where it can run, free-threaded where it cannot - TOML and JSON go through the Rust-based
rtoml and orjson below Python 3.14, and through tomli (3.14) or stdlib tomllib (3.15+) and stdlib
json on 3.14+ and on free-threaded builds (3.14t, 3.15t), with the same results either way.
Extensible formats - TOML and JSON are built-in; YAML is available via the optional yaml extra.
Automation-friendly CLI - inspect, deploy, or scaffold configurations without writing Python.
Structured logging - adapters emit trace-aware events without polluting the domain layer.
Built for AI agents too - the library is designed to be driven by an LLM agent as well as a human, and ships a Claude Code skill (skills/python-layered-config/) that teaches an agent how to install it, design config files, compute the env-var override names, manage profiles, and trace where each setting came from, across Linux, macOS, and Windows. Install it with /plugin marketplace add bitranox/lib_layered_config then /plugin install lib_layered_config.
Installation
pip install lib_layered_config
# or with optional YAML support
pip install "lib_layered_config[yaml]"
# on Python 3.14+ with the GIL (never on a free-threaded build), opt back into the Rust-based parsers
pip install "lib_layered_config[rtoml,orjson]"
Requires Python 3.10+, free-threaded 3.14t and 3.15t included. Below 3.14 rtoml and orjson are
installed and used. From 3.14 they are optional extras, because neither ships a free-threaded build and
importing one would turn the GIL back on: without them, or on any free-threaded interpreter, the library
parses TOML with tomli (a dependency on 3.14) or stdlib tomllib (3.15+) and JSON with stdlib json,
refusing the same files the Rust parsers refuse. Do not install the extras on a free-threaded build: they have
no free-threaded wheel, and the library never imports them there. The one difference is TOML depth past 80
levels: a single table header or inline table 81 to 100 levels deep (a dotted key up to 101 keys) loads there
and is refused by rtoml, while tables nested past 101 levels inside an array of tables load with rtoml and
are refused there.
Install the optional yaml extra only when you actually ship .yml files to keep the dependency footprint small.
For local development add tooling extras:
pip install "lib_layered_config[dev]"
Why we recommend uv: supply-chain protection
This repository commits a uv.lock. It pins every package the project needs, transitive
dependencies included, to an exact version and to the hashes of that version's files. The
exclude-newer setting under [tool.uv] in pyproject.toml adds a cooldown: uv leaves any
release younger than that out of the lock. CI installs from the lock, so a hijacked release that
gets pulled again within the cooldown never reaches our builds, and a file whose hash does not
match is refused.
That protection stays in this repository. The installable package declares only lower bounds
(>=) for its dependencies, so a plain pip install takes the newest release of every transitive
dependency at the moment you run it. If one of them was hijacked an hour earlier, you get the
hijacked version. pipx install and uv tool install without options do the same.
To install the command line tool with a cooldown of your own (uv then skips any release younger
than 7 days, transitive ones included), or to run the exact tree our CI tests:
If you depend on lib_layered_config in your own project, give that project the same cooldown (7 days here, as
an example) and commit the uv.lock that uv add lib_layered_config writes:
Understanding Key Identifiers: Vendor, App, Slug, and Profile
Four identifiers decide where your configuration lives: vendor and app (used in
the macOS and Windows paths), slug (the Linux directory and the environment-variable
prefix), and an optional profile (test / staging / production, each in its own tree).
All four are validated for cross-platform filesystem safety.
Full detail - platform path tables, naming rules, profiles, and validation - is in
docs/identifiers.md.
from lib_layered_config import read_config
# vendor/app -> macOS + Windows paths; slug -> Linux paths + the CONFIG_KIT___ env prefix
config = read_config(vendor="Acme", app="ConfigKit", slug="config-kit", profile="production")
Configuration File Structure
Configuration files are TOML by default (JSON and YAML are also supported). Top-level keys,
[section] tables, nested subtables, and arrays all map onto dotted-path access
(config.get("database.pool.size")) and onto environment-variable overrides
(MYAPP___DATABASE__POOL__SIZE for the slug myapp).
The full annotated example - every structural feature and how each maps to Python access and
to env vars - is in docs/config-file-structure.md.
First .env found via upward search plus platform extras
5
env
Process environment with namespacing and __ nesting
Use the optional defaults layer when you want one explicitly-provided file to seed configuration before host/user overrides apply.
Important directories (overridable via environment variables):
Linux
Also used, for reading and deploying alike, on every platform without a layout of its own (FreeBSD,
Solaris, Cygwin and other sys.platform values that are neither macOS nor Windows).
.env search: current directory upwards + %APPDATA%\<Vendor>\<App>\.env
Environment overrides: LIB_LAYERED_CONFIG_ETC, LIB_LAYERED_CONFIG_PROGRAMDATA, LIB_LAYERED_CONFIG_APPDATA, LIB_LAYERED_CONFIG_LOCALAPPDATA, LIB_LAYERED_CONFIG_MAC_APP_ROOT, LIB_LAYERED_CONFIG_MAC_HOME_ROOT. Both the runtime readers and the deploy helper honour these variables so generated files land in the same directories that read_config inspects. Each must be an absolute path: an empty or relative value makes a read, and a deploy to that layer, raise LayerRootNotAbsoluteError (a ValidationError) before anything is read or written, so no layer resolves under the current directory. A deploy to another target still runs: when it reads its permission settings, a layer with no usable root holds none. $XDG_CONFIG_HOME follows the XDG Base Directory specification instead: empty or relative, it is ignored and ~/.config is used.
Fallback note:~/.config stands in when $XDG_CONFIG_HOME is unset, empty or relative; an absolute value is used even when that directory does not exist. On Windows the user layer reads %APPDATA%\<Vendor>\<App> when it holds a configuration file and %LOCALAPPDATA%\<Vendor>\<App> otherwise, and a deploy writes under %LOCALAPPDATA% only when the %APPDATA% directory does not exist and LIB_LAYERED_CONFIG_APPDATA is not set. This keeps local installs working without additional environment configuration while still allowing operators to steer resolution explicitly.
The .d Directory Pattern
Any configuration file can have a companion .d directory for split configuration. This follows the common Linux pattern (similar to /etc/apt/sources.list.d/ or /etc/sudoers.d/).
Naming convention: The .d directory name is the filename without extension plus .d:
config.toml → config.d/
defaults.toml → defaults.d/
myapp.yaml → myapp.d/
settings.json → settings.d/
A layer's base file is always TOML (config.toml, hosts/<hostname>.toml): a config.yaml or config.json beside it is not read. A layer takes YAML and JSON in its config.d/, and a default_file may be any of the three formats (myapp.yaml loads with myapp.d/).
How it works:
The loader first loads the base file (e.g., config.toml) if present
Then loads all files from the .d directory (e.g., config.d/) in lexicographic order of their
exact names, the same on every OS: digits first, then upper case, then lower case (Z.toml before a.toml)
Only files with supported extensions are loaded: .toml, .json, .yaml, .yml
Files are merged in order, so later files override earlier ones
Both the base file and .d directory are optional - either can exist independently
Supported at all layers: The .d directory pattern works for app, host, and user layers:
Layer
Base File
Companion .d Directory
app
/etc/xdg/myapp/config.toml
/etc/xdg/myapp/config.d/
host
/etc/xdg/myapp/hosts/server-01.toml
/etc/xdg/myapp/hosts/server-01.d/
user
~/.config/myapp/config.toml
~/.config/myapp/config.d/
Host-specific .d directories: Each hostname file can have its own .d directory for per-host split configuration:
File ordering: Use numeric prefixes to control load order:
config.d/
├── 10-base.toml # Loaded first (lowest precedence)
├── 20-database.yaml # Loaded second (mixed formats allowed!)
├── 30-logging.json # Loaded third
└── 99-overrides.toml # Loaded last (highest precedence within config.d)
Precedence order:
config.toml # Loaded first (lowest precedence)
config.d/10-base.toml # Loaded second
config.d/20-db.yaml # Loaded third
config.d/99-local.toml # Loaded last (highest precedence)
Use cases:
Package managers can drop configuration snippets without modifying the main file
Automation tools can add/remove specific settings independently
Team workflows can split configuration by concern (database, logging, features)
CI/CD pipelines can deploy environment-specific overrides as separate files
Default files (--default-file) also support .d expansion
Example:
# Main config defines defaults
/etc/myapp/config.toml:
[database]
host = "localhost"
port = 5432
# Ops team adds production overrides (can use any supported format)
/etc/myapp/config.d/50-production.toml:
[database]
host = "db.prod.example.com"
pool_size = 20
# Monitoring team adds their settings as YAML
/etc/myapp/config.d/60-monitoring.yaml:
monitoring:
enabled: true
endpoint: "https://metrics.example.com"
# Result: database.host = "db.prod.example.com", database.port = 5432,
# database.pool_size = 20, monitoring.enabled = true
With default files:
# defaults.toml and defaults.d/ are both loaded
config = read_config(
vendor="Acme",
app="MyApp",
slug="myapp",
default_file="./defaults.toml", # Also checks ./defaults.d/*.{toml,json,yaml,yml}
)
Without base file (.d directory only):
# No config.toml exists, only config.d/ directory
/etc/myapp/config.d/
├── 10-database.toml
├── 20-cache.toml
└── 30-logging.yaml
# This works! All files from config.d/ are loaded and merged.
CLI Usage
The command-line interface mirrors the Python API: read and inspect configuration, deploy
files across the app/host/user layers, scaffold example trees, and compute environment
prefixes. It also documents the file-overwrite and backup behavior and the per-layer
permission and secret-handling guidance. deploy sets each layer's modes from
--dir-mode/--file-mode, the configured [lib_layered_config.default_permissions], or the
built-in 755/644 and 700/600, applies them to each file it writes, and refuses any mode that
would let the group or the world write a file that can hold credentials.
read_config(...) is the main entry point; it returns an immutable Config with
dotted-path access and per-key provenance. The Config class, the Layer enum, the other
read functions, deploy_config, example generation, profile validation, and the permission
constants are all covered in the full reference.
from lib_layered_config import read_config
config = read_config(vendor="Acme", app="ConfigKit", slug="config-kit")
timeout = config.get("service.timeout", default=30)
print(config.origin("service.timeout")) # which layer and file set it
Example Generation & Deployment
Use the Python helpers or CLI equivalents:
from pathlib import Path
from lib_layered_config import deploy_config, generate_examples
# copy one file into the system/user layers
# If ./myapp/config.d/ exists, those files are also deployed to each destination's config.d/
results = deploy_config(
"./myapp/config.toml", vendor="Acme", app="ConfigKit", slug="config-kit", targets=("app", "user")
)
# scaffold an example tree for documentation
examples = generate_examples(Path("./examples"), slug="config-kit", vendor="Acme", app="ConfigKit")
Deploying with .d Directories
When deploying a configuration file, any companion .d directory is automatically included:
The JSON output includes separate fields for .d file results:
dot_d_created: Paths of .d files created
dot_d_overwritten: Paths of .d files overwritten (with dot_d_backups)
dot_d_kept: Paths of .d files kept unchanged, the new content saved beside them (with dot_d_ucf_files)
dot_d_skipped: Paths of .d files skipped (identical content)
Note: Deployment copies ALL files from the .d directory (including README.md, notes.txt, etc.) to preserve documentation and supporting files. Only config file parsing filters by extension.
User Files Are Preserved During Deployment
Deployment is additive - it only creates or updates files that exist in the source .d directory. User-added files in the destination are never deleted or modified.
# Source .d directory:
config.d/
├── 10-database.toml
└── 20-cache.toml
# Destination before deploy (user added custom files):
/etc/xdg/myapp/config.d/
├── 10-database.toml # ← Will be updated/skipped
├── 20-cache.toml # ← Will be updated/skipped
├── 50-custom.toml # ← USER FILE: untouched
└── 99-local.toml # ← USER FILE: untouched
# After deploy: user files 50-custom.toml and 99-local.toml remain intact
Best Practice: Override in Additional Files
Instead of modifying distributed configuration files directly, add your customizations in a separate file with a high numeric prefix:
# DON'T: Edit the distributed file (changes lost on next deploy)
/etc/xdg/myapp/config.d/10-database.toml # ← Don't modify this
# DO: Create your own override file (preserved across deploys)
/etc/xdg/myapp/config.d/90-local-overrides.toml # ← Add your changes here
Why this approach?
Your customizations survive application updates and re-deployments
Clear separation between distributed defaults and local overrides
Easy to identify what was customized vs. what came from the package
Rollback is simple: just delete your override file
Example workflow:
# Distributed: /etc/xdg/myapp/config.d/10-database.toml
[database]
host = "localhost"
port = 5432
pool_size = 10
# Your overrides: /etc/xdg/myapp/config.d/90-local-overrides.toml
[database]
host = "db.prod.example.com"
pool_size = 50
# port is inherited from 10-database.toml (5432)
Provenance & Observability
Every merged key stores metadata (layer, path, key).
Structured logging lives in lib_layered_config.observability (trace-aware log_debug, log_info, log_warn).
Use bind_trace_id("abc123") to correlate CLI/log events with your own tracing: read_config* and
deploy_config tag every event with the bound id and leave the binding in place for your later events.
Type Conflict Warnings
When a later layer overwrites a scalar value or a list with a mapping (or the reverse), a warning is emitted.
The same holds for a list element, such as MYAPP___DS__0=x over ds = [{a = 1}]:
import logging
logging.basicConfig(level=logging.WARNING)
# If user.toml has: service = "disabled"
# And app.toml has: [service]
# timeout = 30
# A WARNING log is emitted: "type_conflict" with details about the key, layers, and types involved
This helps identify configuration mismatches where a key or a list element changes from a simple value to a nested structure (or the reverse) across layers.
Architecture Overview
The project follows a Clean Architecture layout so responsibilities remain easy to reason about and test:
Layer
Responsibility
Domain
Immutable Config value object plus error taxonomy
Application
Merge policy (LayerSnapshot, merge_layers) and adapter protocols
Adapters
Filesystem discovery, structured file loaders, dotenv, and environment ingress
Composition
core and _layers wire adapters together and expose the public API
Presentation
CLI commands, deployment/example helpers, observability utilities, and testing hooks
uv sync --all-extras # or: pip install -e ".[dev]"
make test # the full local gate
make build # build wheel and sdist artifacts
uv run lib_layered_config --help # run the CLI from the checkout
make test formats with ruff format . and applies ruff check --fix . before it checks, so commit
first if you want to see what it rewrote; CI only checks. Coverage must stay at 90% or above
([tool.coverage.report] fail_under). The development tools and their minimum versions are the dev
extra in pyproject.toml. DEVELOPMENT.md describes every stage of the gate, the
make targets and the release checklist.
Continuous integration
The GitHub Actions workflow executes three jobs:
Test matrix (Linux and Windows on Python 3.10-3.15 plus the free-threaded builds 3.14t and 3.15t, macOS on the newest declared Python) running the same pipeline as make test.
pipx / uv verification to prove the built wheel installs cleanly with the common Python app launchers.
Notebook smoke test that executes notebooks/Quickstart.ipynb to keep the tutorial in sync using the native nbformat workflow (no compatibility shims required).
The CLI runs through lib_cli_exit_tools.cli_session, so the --traceback flag behaves the same locally and in automation. The Python packaging metadata in pyproject.toml is the single source of truth.