Skip to content
Back to skills

Python Layered Config

ASecurity

Use when building or designing configuration for a Python app or CLI with lib_layered_config - deciding where config files live on Linux, macOS, or Windows, choosing the environment-variable override names, writing a .env file or dotenv keys for a config section (SECTION__KEY), adding environment profiles (test/staging/production), loading config in code or from the shell, redacting secrets, or working out which layer and file a setting actually came from (provenance).

  • 3 stars
  • 0 votes
  • 0 copies
  • 4 views
  • Added October 10, 2026
developmentpythonrustgoshellbashsqlnodetestinggitapi

Works with

  • cli
  • api

Security analysis

A96/100
  • mediumInstalls packages at runtime which could introduce malicious dependencies

Pro shows the line behind each finding and how to fix it

Scanned November 27, 2026

npx -y skills add bitranox/lib_layered_config --skill python-layered-config --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Python Layered Config?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Python Layered Config
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/bitranox-python-layered-config/badge)](https://www.skillsdirectory.com/skills/bitranox-python-layered-config)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: python-layered-config
description: Use when building or designing configuration for a Python app or CLI with lib_layered_config - deciding where config files live on Linux, macOS, or Windows, choosing the environment-variable override names, writing a .env file or dotenv keys for a config section (SECTION__KEY), adding environment profiles (test/staging/production), loading config in code or from the shell, redacting secrets, or working out which layer and file a setting actually came from (provenance).
---

# lib_layered_config

Load one immutable configuration object by deep-merging six layers, and be able to say
where every value came from. `lib_layered_config` is a cross-platform config loader for
Python 3.10+ with a matching CLI. It is designed to be driven by an LLM/agent as well as a
human - this skill is that agent guide.

## The core model

Six layers are merged in a fixed precedence, **lowest to highest**:

```
defaults -> app -> host -> user -> dotenv -> env
```

Later layers override earlier ones key-by-key (unrelated keys are kept, not dropped). The
result is a frozen `Config`. Every value records the layer and file that produced it.

Do not forget `defaults` (the lowest layer, seeded from an explicit `default_file`) or that
`env` (process environment variables) wins over everything.

## Install

```bash
pip install lib_layered_config                  # TOML + JSON (rtoml/orjson below 3.14, else stdlib)
pip install "lib_layered_config[yaml]"          # add optional YAML support
pip install "lib_layered_config[rtoml,orjson]"  # Python 3.14+ with the GIL only: the Rust parsers
```

Requires Python 3.10+, free-threaded 3.14t and 3.15t included. Below Python 3.14, `rtoml` and
`orjson` are installed and parse TOML and JSON. On 3.14+ a plain install leaves both out: they are
the optional extras `rtoml` and `orjson` (installed on a GIL build, they are used), because neither
ships a free-threaded build and importing one turns the GIL back on (your own `import orjson` does
the same). Never install the extras on a free-threaded build: they have no free-threaded wheel, so
pip builds them from source or fails, for nothing. Without them, and on every free-threaded
interpreter even when they are installed, the library never imports them, parses TOML with `tomli`
(a dependency on 3.14 and 3.14t) or stdlib `tomllib` (3.15+) and JSON with stdlib `json`, and the
GIL stays off. Both backends give the same values and refuse the same files, except TOML depth: a
single table header or inline table nested 81 to 100 levels deep (a dotted key up to 101 keys) loads
without rtoml and is refused by rtoml; tables deeper than 101 levels are refused everywhere outside
arrays, while inside an array of tables rtoml loads them and the other parsers refuse them. Install
the `yaml` extra only if you ship `.yml` files.

## Load config (Python)

```python
from lib_layered_config import read_config

config = read_config(
    vendor="Acme Corp",
    app="My App",
    slug="my-app",
    default_file="defaults.toml",  # seeds the `defaults` layer (the lowest one)
)
config.get("service.timeout", default=30)  # dotted-path access
config["database"]["host"]  # mapping access
config.origin("service.timeout")  # -> which layer + file set it (provenance)
```

- `vendor` and `app` are used **verbatim** (spaces and case preserved) in the macOS and
  Windows paths.
- `slug` (lowercase-with-hyphens by convention) is the Linux directory name AND the
  environment-variable prefix. It may hold ASCII letters of either case, digits, `.`, `-` and `_`
  and must start with a letter or digit and must not end in `.`, `-` or `_`; anything else is
  refused (`ValidationError`).
- `default_file` seeds the `defaults` layer. It is the ONLY way to supply that layer - omit it
  and there are no defaults at all, whatever the precedence chain says.
- `read_config` returns a frozen `Config`; `read_config_raw(...)` returns `.data` plus
  `.provenance`; `read_config_json(...)` returns a JSON string of config + provenance.

## Where a setting comes from (provenance)

The whole point of the library. To answer "why is this value what it is":

- **Python:** `config.origin("database.host")` returns the layer and file path, a `SourceInfo`
  (exported from `lib_layered_config`, for annotations). Or
  `read_config_raw(...).provenance["database.host"]` -> `{"layer": ..., "path": ..., "key": ...}`.
- **CLI:** `lib_layered_config read-json --vendor "Acme Corp" --app "My App" --slug my-app`
  prints the merged config **and** the provenance map. `read --format json` does the same;
  human output (`read`) prints a `# source:` comment above each value.

**A `--set` style override names itself as the source.** Every key
`with_overrides` supplies reads back from `origin()` as layer `override` (the exported
`OVERRIDE_LAYER`), path `None`, so a caller content with that label needs no provenance code of
its own. Keys it did not touch keep their file. When a scalar replaces a table, the scalar's key
(`db`) reads as `override` and the keys it removed (`db.host`) have no source at all:

```python
from lib_layered_config import Config

cfg = Config({"db": {"host": "a"}}, {"db.host": {"layer": "app", "path": "/etc/app.toml", "key": "db.host"}})
cfg.with_overrides({"db": {"host": "b"}}).origin("db.host")
# {'layer': 'override', 'path': None, 'key': 'db.host'}
```

To label the layer `cli` instead, rebuild provenance for exactly
the keys the override supplied - layer `cli`, path `None` - and leave every other key's source
alone. Four details decide whether that lands:

- the dotted key is the SECTION plus the key path, because a parsed override's key path EXCLUDES
  its section; joining only the key path matches nothing and silently changes no entry.
- overriding a key that no file defined must still record a source, or the key appears with a
  value and no origin at all.
- each provenance entry needs exactly `layer`, `path` and `key`, `key` being its own dotted key
  (`"db.host"`); `Config(...)` refuses anything else with `ValidationError` naming the entry.
- a `Config` you rebuild yourself takes a THIRD argument:
  `Config(data, provenance, NotSensitiveKeys.of(NOT_SENSITIVE))`, built from the same set your
  loader passes to `read_config(not_sensitive=...)`. It defaults to `NotSensitiveKeys.NONE`, so
  leaving it out drops the declaration silently, and a redacted display then masks keys the app
  declared safe. `with_overrides` carries the declaration through; only a hand-built `Config`
  loses it.

Assert it end to end, by running the command and reading the printed source, not by unit-testing
the merge: the merge is correct in isolation, and the defect only exists in what is displayed. Use
an override value that differs from every file layer, so a source still pointing at a file cannot
pass by showing the same value; and when the display redacts, check a declared not-sensitive key
still shows its value.

## Environment-variable overrides (the trap)

An env var overriding a config key is built as:

```
<SLUG_UPPERCASED_WITH_DASHES_AS_UNDERSCORES> + "___" + <SECTION>__<SUBSECTION>__<KEY>
```

- Prefix ends in a **TRIPLE** underscore `___` (separates the app prefix from the key path).
- Key-path segments are joined by a **DOUBLE** underscore `__`. A leading, trailing or doubled `__`
  (`MY_APP___DATABASE__`, `MY_APP___DATABASE____HOST`) leaves an empty segment and fails the load with
  `LayerLoadError` naming the variable, in the environment and `.env` alike.

So for `slug="my-app"`, the key `database.host` is set by **`MY_APP___DATABASE__HOST`**
(not `MY_APP_DATABASE__HOST`, not `MYAPP___...`). Compute the prefix with
`lib_layered_config env-prefix my-app` (the slug is POSITIONAL; prints `MY_APP___`) or
`default_env_prefix("my-app")` in Python.

- Values coerce: `true`/`false` -> bool, `null`/`none` -> None, ints/floats, else string. A sensitive key
  (one `redact=True` masks: `password`, `token`, `secret`, `*_key`) keeps `null`/`none` as text
  unless declared with `read_config(not_sensitive=[...])` (a path matches in any case, so
  `"db.dbPassword"` covers `db.dbpassword`); a number under a sensitive key still converts.
  A variable's or `.env` key's name arrives lowercased, so the key is judged in the spelling a lower
  layer stored for it: `MY_APP___DB__DBPASSWORD=null` overrides a file's `dbPassword` (case does not
  matter) and sets it to `"null"`, since the case change splits it into `db` + `password`, just
  as `MY_APP___DB__DB_PASSWORD=null` sets `db_password` to `"null"`. A key no lower layer holds is
  judged on its lowercase name and stored under it: `db.dbpassword` is one word, so None.
- A value starting with `[` or `{` is parsed as JSON, in the environment AND unquoted in `.env`
  (`REPLICAS='["a","b"]'` in a shell, `REPLICAS=["a","b"]` in `.env`); a quoted `.env` value is always literal
  text; a comma list is never split.
- A number converts only when it reads back as the same text: `5` and `3.5` do, `007123`, `0640` and `1.50`
  stay strings.
- So an unquoted digit-only value with no leading zero (`DIR_MODE=2770`, a uid, an all-digit password)
  arrives as an `int`, in `.env` and the environment alike; the sensitive-key rule protects only
  `null`/`none`, never a number. A pydantic `str` field then fails startup with
  `Input should be a valid string [type=string_type, input_value=2770, input_type=int]`. Put
  `model_config = ConfigDict(coerce_numbers_to_str=True)` on one shared base class for every section
  model, not per field: the conversion is lossless, so the text comes back exactly as written, `int`
  fields stay ints, and field validators still check the text. Quoting the value fixes only that one
  line, and the next digit-only value breaks startup again. Pin it with a test that writes a real
  `.env` through the real loader and asserts the raw value is an `int` before the model parses it.
- A `.env` key is the key path WITHOUT the prefix: `DATABASE__HOST=db1`. A `MY_APP___DATABASE__HOST` line in
  `.env` does not override `database.host`; it creates a separate `my_app` section. Case does not
  matter, and a single `_` stays inside a name: `CAL_STORE__HOST=h1` sets `cal_store.host`.
- An unquoted `.env` value converts exactly like an environment value; a quoted one stays literal text.
- A numeric segment overrides one element of a file-defined array:
  `MY_APP___DATASET__0__DSN=...` overrides element 0's `dsn`, leaving the rest of the array.

## Per-OS config paths

Each layer resolves to a `config.toml` (`hosts/<hostname>.toml` for host), always TOML: a
`config.yaml` or `config.json` beside it is not read. YAML and JSON go in the layer's optional
companion `config.d/` directory, which takes `.toml`, `.json`, `.yaml` and `.yml` files.
`<Vendor>`/`<App>` are verbatim; `<slug>` is the slug.

| Layer  | Linux                                   | macOS                                                      | Windows                                    |
|--------|-----------------------------------------|------------------------------------------------------------|--------------------------------------------|
| app    | `/etc/xdg/<slug>/config.toml`           | `/Library/Application Support/<Vendor>/<App>/config.toml`  | `%ProgramData%\<Vendor>\<App>\config.toml` |
| host   | `/etc/xdg/<slug>/hosts/<hostname>.toml` | `.../<Vendor>/<App>/hosts/<hostname>.toml`                 | `...\<Vendor>\<App>\hosts\<hostname>.toml` |
| user   | `~/.config/<slug>/config.toml`          | `~/Library/Application Support/<Vendor>/<App>/config.toml` | `%APPDATA%\<Vendor>\<App>\config.toml`     |
| dotenv | `~/.config/<slug>/.env`                 | `~/Library/Application Support/<Vendor>/<App>/.env`        | user `%APPDATA%\<Vendor>\<App>\.env`       |
| env    | process environment, prefix `<SLUG>___` | same                                                       | same                                       |

Notes: Linux `app`/`host` also read `/etc/<slug>/...`, after `/etc/xdg/<slug>/...`, so a key set in both
takes the `/etc/<slug>` value; Linux honours
`$XDG_CONFIG_HOME` for the user layer; Windows reads the user layer from
`%LOCALAPPDATA%\<Vendor>\<App>` when the `%APPDATA%` one holds no config file. Roots are
overridable for tests (`LIB_LAYERED_CONFIG_ETC`, `LIB_LAYERED_CONFIG_PROGRAMDATA`,
`LIB_LAYERED_CONFIG_MAC_APP_ROOT`, `LIB_LAYERED_CONFIG_MAC_HOME_ROOT`,
`LIB_LAYERED_CONFIG_APPDATA`, `LIB_LAYERED_CONFIG_LOCALAPPDATA`).

The dotenv row is only the LAST place searched. The dotenv layer first looks for `.env` in
`start_dir` and in every parent up to the filesystem root (the current directory and its parents
when `start_dir` is not given; a RELATIVE `start_dir` is not resolved, so its search covers
`start_dir` and its relative parents and ends at the current directory, not above it), then at the
per-user path above, and loads only the first file it finds. On Linux and macOS every searched
`.env` (in `start_dir`, its parents and the per-user path) must be owned by the process's effective
user or by root (for a symlink, both the link and the file it points to). Any other file does not
count as found: it is passed over with a WARNING record `dotenv_skipped_foreign_owner` on the
`lib_layered_config` logger (`record.context` holds its `path` and `owner_uid`), and the search goes
on to the next candidate. So a `.env` another user put in `/tmp` is never loaded, and a process
running as root (`sudo` in a project directory) passes over that user's own `.env`. Only the owner
is checked, never the mode: a `.env` you own loads even when it is group- or world-writable. Windows
has no such check. On every OS, Windows included, a searched `.env` with more than one hard link is
passed over the same way, with a WARNING record `dotenv_skipped_hard_link` on the same logger
(`record.context` holds its `path` and `link_count`), and the search goes on to the next candidate:
a hard link keeps the owner of the file it links to. So a real `.env` that also has a second link (a
`cp -al` backup tree) is not loaded by the search; name it with `dotenv_path=` instead.
`dotenv_path=` (CLI `--env-file`) loads that one file with no search and no owner or link check. It
may be a regular file, a FIFO such as a shell process substitution
(`--env-file <(printf 'KEY=value')`), or a device. Every config file has the same 10 MiB cap:
exactly 10 MiB (10485760 bytes) loads, one byte more is refused, and an endless source such as
`/dev/zero` is refused after reading one byte past the cap. Like `cat`, a FIFO read waits for its
writer and for it to close, with no timeout: a writer that never closes blocks the read forever. In
Python a `dotenv_path=` that does not exist loads nothing (an empty dotenv layer, no error); the
CLI's `--env-file` refuses a missing path as a usage error (exit 2). A directory is refused either
way.

## Probing and testing an app built on it

- **A probe or test started inside a repo loads that repo's `.env` secrets.** A `read_config`
  probe, the app's CLI, or its pytest run from a repo root finds the repo's local `.env` (upload
  tokens, passwords) by the upward search, and `config.as_dict()`, a full provenance dump or a
  pytest assertion diff prints them. A gitignored `.env` is absent in a fresh git worktree, so a
  test can pass there and leak in the main checkout's gate. Run probes from an empty temp
  directory and pass `start_dir=` that directory (or `dotenv_path=` a test file); in tests anchor
  every `start_dir` under `tmp_path` (or `monkeypatch.chdir(tmp_path)` first), never a relative
  path. Print only what the question is about (`config.get(key)`, `config.origin(key)`), or use
  `as_dict(redact=True)` / `to_json(redact=True)`. To isolate a run from every deployed layer
  too, point `HOME`, `XDG_CONFIG_HOME`, `APPDATA`, `LOCALAPPDATA` and the
  `LIB_LAYERED_CONFIG_*` roots above into that temp directory, and any network endpoint the app
  reads at a closed local port (`127.0.0.1:1`). Strip every inherited `LIB_LAYERED_CONFIG*` and
  `<SLUG>___` variable from the copied environment first, then set all six roots. The three APP
  roots are the ones a partial setup misses, `LIB_LAYERED_CONFIG_ETC`,
  `LIB_LAYERED_CONFIG_MAC_APP_ROOT` and `LIB_LAYERED_CONFIG_PROGRAMDATA`: each platform reads only
  its own, so a test that sets one is isolated on one OS and reads the deployed config on the
  others. The OS variable `ProgramData` (in any case, `PROGRAMDATA` too) also moves the Windows
  app root, but `LIB_LAYERED_CONFIG_PROGRAMDATA` wins over it, so set the override. Every Windows
  root must be an absolute path: a relative value raises `lib_layered_config.ValidationError`
  before anything is read or written, and so does a test on Linux or macOS that forces the Windows
  layout (`deploy_config(..., platform="win32")`, `deploy --platform windows`) for the `app` or
  `host` target with neither variable set, because the built-in `C:\ProgramData` is relative
  there. A `user`-only deploy needs no ProgramData root and no variable at all: the `APPDATA` and
  `LOCALAPPDATA` defaults sit under the home directory, which is absolute everywhere. The POSIX
  overrides follow the same rule: an empty or relative `LIB_LAYERED_CONFIG_ETC`,
  `LIB_LAYERED_CONFIG_MAC_APP_ROOT` or `LIB_LAYERED_CONFIG_MAC_HOME_ROOT` raises
  `LayerRootNotAbsoluteError` (a `ValidationError`) naming the variable, on a read and a deploy
  alike (each on the platform whose layout uses it), before anything is read or written, while a
  relative `XDG_CONFIG_HOME` is ignored, as
  the XDG spec says, and the user layer stays under `~/.config`.
- **A Windows user-layer deploy whose `%APPDATA%` directory does not exist writes under
  `%LOCALAPPDATA%` instead.** `deploy --target user` (and `deploy_config(..., targets=["user"])`)
  on Windows writes `%LOCALAPPDATA%\<Vendor>\<App>\config.toml` whenever the `%APPDATA%`
  directory is MISSING and `LIB_LAYERED_CONFIG_APPDATA` is unset; Linux and macOS have no such
  fallback. A fixture that sets `APPDATA` to a `tmp_path` subdirectory it never creates sends
  every Windows deploy elsewhere: a "file was written" check fails with the file not found, and
  a "the refused deploy wrote nothing" check passes whatever the deploy did. Create the
  directory in the fixture (`roaming.mkdir(parents=True)`), or set `LIB_LAYERED_CONFIG_APPDATA`,
  which disables the fallback.
- **Configured permission modes are not read on Windows.** Windows applies no modes, so a deploy
  there never reads `[lib_layered_config.default_permissions]` and cannot refuse an unsafe
  configured mode; it deploys. An explicit `--dir-mode`/`--file-mode` (`dir_mode=`/`file_mode=`)
  or a `permission_overrides` mode (what an app's `--set` passes) is still validated on every
  platform. Mark a test of a configured-mode refusal POSIX-only, and pin the Windows behaviour in
  its own arm: the deploy proceeds.

## Running as a systemd service (ProtectHome)

A layer path that exists but cannot be read is a load error, not a skipped layer: `read_config`
raises `LayerLoadError` (`.../<slug>/.env cannot be read: Permission denied`), while a path that
does not exist is skipped. `ProtectHome=yes` (or `true`) makes `/home`, `/root` and `/run/user`
inaccessible to the service, so the user layer and the per-user `.env` under the service user's
home fail with that error at every start, even when the home was never created; an app that
reports a configuration error as EX_CONFIG exits 78. Use `ProtectHome=tmpfs` instead: the homes
stay hidden but are mounted empty, so the user layer is simply absent. `ProtectHome=read-only`
also loads. A plain `runuser -u <user>` check does not show the failure (outside the sandbox a
missing home is absent, not unreadable): run the app's config command under the unit's own
properties, `systemd-run --wait --pipe --collect -p User=<user> -p ProtectHome=<value> <app>
config`, and require exit 0.

## Profiles (per-environment config)

A profile keeps test/staging/production in separate trees. Pass `profile=`:

```python
config = read_config(vendor="Acme Corp", app="My App", slug="my-app", profile="production")
```

This inserts a `profile/<name>/` segment into every layer path, e.g.
`/etc/xdg/my-app/profile/production/config.toml`. Without a profile you get the base paths.
The segment REPLACES the base paths, it is not added beside them: with a profile, the plain
app, host and user files (and the per-user `.env`) are not read at all. Only the `defaults` file
you pass, a `.env` found by the upward search and the environment still apply. So a profile file
holding a single override loses every other setting the base files carried (a base
`config.toml` with `[node] host = "pve1"` plus `profile/site-b/config.toml` holding only `[ssh]
known_hosts_file` reads, under `--profile site-b`, with no `node.host` at all). Make each profile
file the site's whole configuration, and name the section of every key in an example.
Profile names are validated (no path traversal, control chars, reserved names, non-ASCII;
max 64 chars). `--profile` is an OPTION (on `read`, `read-json` and `deploy`), not a command -
the required flags come too: `deploy --source cfg.toml --vendor acme --app my-app --slug my-app
--target user --profile production`.

## CLI commands

Same engine as the library. Run any command with `-h` for full flags.

| Command             | Purpose                                                                                                                                                                                 |
|---------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `read`              | Load and print config (human by default; `--format json`; secrets masked unless `--no-redact`).                                                                                         |
| `read-json`         | Print merged config + provenance as JSON.                                                                                                                                               |
| `deploy`            | Copy a `.toml` config file into app/host/user layers (`--target`, `--profile`, `--force`/`--batch`, `--dir-mode`/`--file-mode`, `.bak`/`.ucf` conflict handling, permission hardening). |
| `generate-examples` | Scaffold an example config tree to bootstrap a project.                                                                                                                                 |
| `env-prefix`        | Print the `<SLUG>___` env-var prefix for a slug.                                                                                                                                        |
| `info`              | Print resolved package metadata.                                                                                                                                                        |
| `fail`              | Raise a deliberate `RuntimeError`, to test how a harness reports a failing command.                                                                                                     |

Flags are PER-SUBCOMMAND, not CLI-wide - run `<cmd> -h` before composing a call:

| Flag                                                                                           | read | read-json | deploy | generate-examples | env-prefix | info |
|------------------------------------------------------------------------------------------------|------|-----------|--------|-------------------|------------|------|
| `--vendor` / `--app` / `--slug`                                                                | yes  | yes       | yes    | yes               | no         | no   |
| `--profile`                                                                                    | yes  | yes       | yes    | no                | no         | no   |
| `--env-file <path>` (load an explicit `.env`)                                                  | yes  | yes       | no     | no                | no         | no   |
| `--default-file <file>` (defaults layer)                                                       | yes  | yes       | no     | no                | no         | no   |
| `--start-dir <dir>` (.env search start)                                                        | yes  | yes       | no     | no                | no         | no   |
| `--format human\|json`, `--provenance` / `--no-provenance`                                     | yes  | no        | no     | no                | no         | no   |
| `--redact` / `--no-redact` (secrets masked by default)                                         | yes  | yes       | no     | no                | no         | no   |
| `--json` (one JSON envelope `{ok, command, data, skipped}`; on failure `{ok, command, error}`) | yes  | yes       | yes    | yes               | yes        | yes  |

`env-prefix`, `info` and `fail` accept only `--json` and `--help` (`env-prefix` takes a positional
SLUG). Passing one of the others raises `NoSuchOption`.

While a command runs, the library's warnings go to stderr, one line each, as
`warning: <event> key=value ...`: for example `warning: type_conflict key=a layer=user path=...
old_type=scalar new_type=mapping` when a user-layer table replaces an app-layer value, or
`dotenv_skipped_foreign_owner` and `deploy_setting_ignored`. Stdout and the `--json` envelope do not
change, so parse stdout and read stderr as diagnostics. A line names keys, paths, layers and types,
never a configuration value.

## Designing config files

- **Structure maps to access and to env vars.** A `[database]` section with `host = "..."`
  is read as `config.get("database.host")` and overridden by `MY_APP___DATABASE__HOST`. A
  `[database.pool]` subtable's `size` is `database.pool.size` / `MY_APP___DATABASE__POOL__SIZE`.
- **Keep secrets OUT of committed files.** Put passwords/tokens in the `env` layer or a
  `.env` file (both outrank the committed config); the CLI masks secrets unless given
  `--no-redact`; use `Config.to_json(redact=True)` when printing or logging from code (the Python
  calls, `read_config_json` included, mask only when given `redact=True`). A key whose name only
  LOOKS secret (`max_token_bytes`) is declared with
  `read_config(..., not_sensitive=["performance.max_token_bytes"])`; the returned Config shows it
  under `redact=True` and in `display_config`.
- **Split large config with `.d/`.** `config.toml` may have a companion `config.d/` whose
  files (`10-db.toml`, `20-cache.yaml`, ...) load in lexicographic order and can mix formats.
  Either can exist without the other: a `config.d/` with no `config.toml` beside it still loads.
- **Quote YAML keys that look like numbers or booleans** (`'1':`, `'true':`): an unquoted one is not a
  string key, and the loader refuses the whole file.
- **Write ordered YAML as a plain mapping, never `!!omap` or `!!pairs`**: a plain mapping keeps the
  file's key order through `read_config` and `as_dict()`, while those two tags load as `(key, value)`
  tuples whose keys redaction cannot see, so the loader refuses the whole file.
- **Write a set as a list and binary data as a base64 string, never `!!set` or `!!binary`**: those
  load as a Python `set` and `bytes`, which no JSON view can carry, so the loader refuses the whole file.
- **Write an integer outside `-2**63` to `2**64-1` as a string**: no JSON view can write one, so a TOML
  or YAML file holding it is refused whole, naming each integer's position and width.
- **Use profiles for environments**, not copy-pasted files.
- **Scaffold** a starting tree with `generate-examples` rather than hand-building paths.

## Writing one value back into a layer

Inside one layer the base file loads first, then every `.toml`, `.yaml`, `.yml` and `.json` file of
its `config.d/` in sorted name order, a later file winning key by key. So a value written into
`config.toml` is silently beaten by the same key in any `config.d/` file of that layer, and by
every higher layer (`dotenv`, `env`, an override). To write a setting from code (a `calibrate set`
command, a setup wizard):

1. List the layer's files in load order: its base file, the one path `deploy_config_paths(<the
   app's default config file>, vendor=..., app=..., slug=..., targets=["user"])` returns outside a
   `.d` directory (pass `profile=` when the app runs with one), then the files in the `config.d/`
   beside it on disk, sorted by name.
2. Write into the LAST of those files that already sets the key; when none does, into the base
   file. Edit it with a library that round-trips (tomlkit for TOML keeps comments and order), never
   by text substitution.
3. Re-read through the loader (an app that caches its loaded configuration must drop that cache
   first) and compare `config.get(key)` with the value written. If they differ,
   `config.origin(key)` names the layer and file still winning (a `.env`, an environment variable,
   another file): report that to the user rather than writing past it.

## Python API beyond read_config

Everything below is importable from `lib_layered_config`, unless a line names another module.

**Errors.** Catch `ConfigError`, the base of every error the library defines. `read_config*`
wraps a layer file it cannot read in `LayerLoadError` (see "Running as a systemd service"): follow
`__cause__` until you reach an `OSError` (the `PermissionError`, two links down, past an
`InvalidFormatError`); a file that does not parse has no `OSError` in that chain. `deploy_config`
lets `FileNotFoundError` and `PermissionError` through as themselves. Wrong-argument errors
(`TypeError`, `KeyError`) reach you as themselves. The subclasses of `ConfigError`:

- `LayerLoadError` - `read_config*` could not read, decode or parse a layer file (broken TOML,
  invalid UTF-8, a malformed `.env` line), or the loader refused one (a rule under "Designing
  config files"), or a layer holds a `.yaml` file and the `yaml` extra is not installed; from
  `deploy_config`, a source that is not TOML, or a `.d` file that does not parse or is YAML with
  no `yaml` extra.
- `InvalidFormatError` - a source cannot be parsed. `read_config*` re-raises it as `LayerLoadError`,
  so you meet it directly only from lower-level calls (nesting deeper than the limit in
  `redact_mapping`, for example).
- `NotFoundError` - an optional source is unavailable (a file that is not there). A `.yaml` file
  on a host without the `yaml` extra is not skipped: every read and deploy raises `LayerLoadError`
  naming the file and `lib_layered_config[yaml]`.
- `ValidationError` (also a `ValueError`) - an identifier or profile name is refused, or a layer
  root is not an absolute path (its subclass `LayerRootNotAbsoluteError`). Its subclasses
  `DeployModeError` (an unsafe or malformed mode, or `dir_mode`/`file_mode` given together with
  `set_permissions=False`), `DeployPermissionsError` (unusable permission settings, one line per
  problem; `.problems` holds one `PermissionProblem` each, with `.key`, `.reason` and `.source`, a
  `str`: the path of the file that set the key, else its layer name, `"override"` for a
  `permission_overrides` value, or `None`) and
  `DeployDestinationError` (a file deploy would write is a symbolic link, dangling or
  not, or not a regular file, or it cannot be created because a file stands where a directory
  belongs, `<path> cannot be created: <ancestor> is not a directory`, or no directory above it
  exists, as on a missing Windows drive; one line each, nothing is written) come from deploy.
  `GenerateDestinationError`, the same refusal for an example path, comes from
  `generate_examples`.
- `HomeDirectoryUnknownError` (also a `RuntimeError`) - the home directory cannot be determined
  (`HOME` unset and no passwd entry, as for a container user). `deploy_config` and
  `deploy_config_paths` raise it for the `user` target; a read skips the user layer and warns.

**Redaction helpers.** `is_sensitive("smtp_password")` -> `True` checks one key NAME against the
built-in patterns (a field named just `key` is not sensitive). The patterns are `password`,
`passwd`, `passphrase`, `pwd`, `pass`, `secret`, `token`, `credential`, `apikey`, `privatekey`,
`privkey`, `bearer`, `cookie`, `jwt`, `signature`, `session_id`, `authorization` and any `_key`
suffix, matched per word after splitting at `_`, `-`, `.`, whitespace and a change of case, with
plurals and trailing digits: `db_pwd`, `smtpPass`, `client-secret`, `apiKey2` and `password2` are
sensitive, and a table under such a name is masked whole. A name that only looks secret
(`pass_through`, `token_url`) is masked too; keep it visible by its dotted path with
`read_config(not_sensitive=["features.pass_through"])`, a Python-only declaration (no CLI flag or
config key can unmask a value). A declared path shows its own value, a URL password in it
included, so declare only a path that holds no secret; keys below a declared table are still
judged by name (`token` under it stays masked).
`str(config)` and `repr(config)` print the redacted view, so `logger.debug("loaded %s", config)`
shows no secret.
`is_sensitive_at(("performance", "max_token_bytes"), not_sensitive=NotSensitiveKeys.of([...]))`
checks a key PATH and honours a declaration; pass a tuple of segments, never a dotted `str`
(refused with `TypeError`). Its `not_sensitive` takes a `NotSensitiveKeys` or the dotted paths
themselves (`not_sensitive=["performance.max_token_bytes"]`), as `redact_mapping` does; a single
`str` there is refused with `TypeError` too.
`redact_mapping(data, not_sensitive=["performance.max_token_bytes"])` returns a masked deep copy
of any Mapping (a dict, a `Config`); `not_sensitive` takes dotted paths or a `NotSensitiveKeys`.
It does not read a `Config`'s own declaration, so pass `not_sensitive` again, or use
`config.as_dict(redact=True)`, which honours it. Use it on
`read_config_raw(...).data`, which does not carry the declaration. `config.get_redacted("db.password")`
returns one value as `as_dict(redact=True)` shows it (a key below a masked section is masked too, a
declared not-sensitive path stays visible), redacting only that key's path rather than copying the
whole configuration; it takes `default=` like `get`. A masked value reads
`REDACTED_PLACEHOLDER` (`"***REDACTED***"`); compare against the constant, not the literal.

**A mask keyed on the value's type leaks.** A value starting with `[` or `{` in the environment or
unquoted in `.env` is parsed as JSON, so a setting documented as text can arrive as a list, a
table, a number, a bool or None. An app-written mask guarded by `isinstance(value, str)` passes a
password wrapped in a list (`'["postgresql://user:pw@db.example/app"]'`) straight through, in every
output mode. Mask by KEY, whatever the value's shape: `redact_mapping` and `redact=True` already
mask a sensitive-named key whatever its value and recurse into nested mappings, lists and tuples.
A URL's password (`scheme://user:pw@host`) in a string value is masked under any key, a `url`
included, by `redact_mapping` and every `redact=True` view (`as_dict`, `to_json`, the CLI), for
every URL the string holds (`amqp://u:p1@h1//;amqp://u:p2@h2//` masks both).
A bare secret under a key whose name matches no built-in pattern (a `conn` holding a password:
`is_sensitive("conn")` is `False`) is masked by neither, so your own mask must name it and mask
every shape; only None, which carries no secret, may show. Such a key reads an unquoted
`null`/`none` as None, while a sensitive-named key keeps them as text (see "Environment-variable
overrides") and is masked anyway. Refuse a non-text value for a text setting at the boundary,
naming the setting and its type, never the value: unrefused, a number or list reaches a text
consumer that uses it anyway (a numeric URL taken as a relative file name). Test each
secret-bearing setting with one arm per shape (string, JSON array, JSON object, number, `null`),
in every output mode, with and without redaction.

**Profiles.** `validate_profile_name("production")` returns the name or raises `ValidationError`;
`is_valid_profile_name(name)` answers `True`/`False` instead. Both take `max_length=` (default `DEFAULT_MAX_PROFILE_LENGTH`, 64).

**Deploying and scaffolding.** `deploy_config("app.toml", vendor=..., app=..., slug=..., targets=["user"])`
is the `deploy` command in Python (`source` is the path of the file to copy). It returns a list with
one frozen `DeployResult` per destination: `.destination`, `.backup_path`, `.ucf_path`,
`.dot_d_results` (a tuple, one `DeployResult` per `.d` copy) and `.action`, an enum; assigning a
field raises `dataclasses.FrozenInstanceError`. Compare `.action.value == "created"` (or
`"overwritten"`, `"kept"`, `"skipped"`, `"conflict"`), since `.action == "created"` is always
`False`. `"skipped"` means the file was already byte-identical; `"conflict"` means it differs and
was left unchanged because no `force`, `batch` or `conflict_resolver=` decided, so key a missed
update on `"conflict"`. A `conflict_resolver(destination)` must return `DeployAction.OVERWRITTEN` or
`DeployAction.KEPT`; any other answer raises `ValidationError`. `force` (overwrite) and `batch`
(keep) decide first: with either set, the resolver is never called, so read what a deploy did from
the returned `DeployResult`s, not from the resolver's calls. Otherwise it is asked once per
differing destination, each differing `.d` copy included. Permission keywords: `set_permissions`,
`dir_mode`, `file_mode`, `permissions=` (a whole `DeployPermissions`) and
`permission_overrides={"user_file": "0o640"}`. `deploy_permissions_from_config(config)` builds a
`DeployPermissions` from a merged config's `[lib_layered_config.default_permissions]`.
`DeployMode(value, kind)` checks one mode by itself, `value` an int such as `0o750` and `kind`
`ModeKind.DIRECTORY` or `ModeKind.FILE` (a file mode also refuses any execute bit). A refused mode
raises `DeployModeError`, which carries no kind field: its message names the kind and every
offending bit (`unsafe file mode 0o777: group write (0o020); world write (0o002); an execute bit on
a file (0o111)`), and a caller that needs the kind already knows which one it passed. `dir_mode`
and `file_mode` each take an int or a `DeployMode` of the matching kind; one of the other kind
raises `DeployModeError` naming both, before anything is written:
`dir_mode: got a file mode (0o640); dir_mode takes a directory mode`. `force=True`
backs up and overwrites an existing file, `batch=True` keeps it and writes a `.ucf`; both at once
raise `ValidationError` (`--force --batch` is a usage error, exit 2), before anything is written.
The source must be a `.toml` file (destinations are `config.toml` / `<hostname>.toml`, read only as
TOML): a `.json`, `.yaml` or `.conf` source raises `LayerLoadError` before anything is written. A
file in the source's `.d` may be any supported format; one that does not parse, or a `.yaml` file
without the `yaml` extra, raises `LayerLoadError` too, so no file of the deploy is written, and a
non-config file (a `README.md`) is copied unparsed. A missing source raises `FileNotFoundError`; a
source or a file in its `.d` directory behind a permission wall raises `PermissionError` on every
Python, before anything is written. Targets are written one after another, in the order `targets`
lists them, so a deploy that fails part-way (a permission wall at the second target, a full disk)
has written the earlier ones; it
raises the original exception unchanged, and `deployed_before_failure(error)` (exported from
`lib_layered_config`) returns the `DeployResult`s already written, in write order (a `.d` copy sits
in its main file's `.dot_d_results`), or `[]` for an error that carries none.

**What a deploy sees, before it runs.** `deploy_config_paths(source, vendor=...,
app=..., slug=..., targets=[...])` returns every file that deploy writes, resolved, as a frozenset:
each target's config file (`config.toml`, or `hosts/<hostname>.toml` for host) plus, in the `.d`
directory beside it (`config.d/`, `hosts/<hostname>.d/`), a copy of each file in the source's own `.d`
(`defaults.d/` for `defaults.toml`).
`read_deploy_config(source, vendor=..., app=..., slug=..., skip=...)` returns the configuration deploy
reads its modes from: the source as defaults, the app, host and user files not in `skip`, the
environment, never `.env`, and only `user_*`/`enabled` from a user file. Pass
`skip=deploy_config_paths(...)` for the deploy's exact read, or a subset (say, only the files that no
longer parse) to read past a broken file a forced deploy will replace; `skip` must be an iterable of
paths, never one bare path (`TypeError`). Both take `profile=`/`platform=` like `deploy_config`, raise
`FileNotFoundError` for a missing source, and a file not skipped (the source included) that does not
parse raises `LayerLoadError`. Then `perms = deploy_permissions_from_config(that_config,
overrides=<what you pass as permission_overrides>)`: `perms.enabled` says whether modes are set at all,
and `perms.for_layer(Layer.APP)` (the `Layer` enum from `lib_layered_config`; `Layer.HOST`,
`Layer.USER` likewise) gives a `LayerModes` whose `.directory` and `.file` (each a `DeployMode` that
prints in octal, such as `0o600`, the user layer's default file mode, and whose `.value` is the `int`
mode) are that layer's modes, unless you pass an explicit `dir_mode`/`file_mode`, which wins.
A deploy sets the directory mode on the directory each file goes into, even one that already
existed, and on every parent it creates; a parent that already existed keeps its mode, and a
directory reached through a symbolic link is left as it is (logged
`deploy_directory_mode_skipped`). The
built-in modes are exported as `DEFAULT_APP_DIR_MODE`/`DEFAULT_APP_FILE_MODE` (`0o755`/`0o644`, app
and host) and `DEFAULT_USER_DIR_MODE`/`DEFAULT_USER_FILE_MODE` (`0o700`/`0o600`, user). Modes
are never applied on Windows, and a deploy there never reads the configured ones (see "Probing and
testing an app built on it"). Use these instead of importing anything from
`lib_layered_config.core`. For one layer's destination without a deploy, build
`DefaultPathResolver(vendor=..., app=..., slug=...)` from
`lib_layered_config.adapters.path_resolvers.default` (optional `profile=`, `hostname=`, `env=`, and
`platform=` for another OS's layout: `"linux"`, `"darwin"` or `"win32"`, or any alias
`deploy_config` takes (`"posix"`, `"macos"`, `"mac"`, `"windows"`, `"win"`, `"wine"`, in any
case, so `"Darwin"` and `"Windows"` work too), the Windows one needing an absolute ProgramData
root, see "Probing and testing an app built on it") and call
`.destination_for(Layer.APP)` on it. It takes the `Layer` enum (`Layer.APP`,
`Layer.HOST`, `Layer.USER`); the name works too in any case, as in `deploy_config` (`"app"`,
which pyright strict flags), and `Layer.ENV` or an unknown name raises `ValidationError`
(`Unsupported deployment target: env`). It returns a
`Path`, never `None`, so an `is None` guard fails pyright strict too.
`generate_examples(destination, slug=..., vendor=..., app=...)` is `generate-examples` and returns
the list of written paths; an example file that already exists is left unchanged and not listed,
unless `force=True` overwrites it. `generate_examples_report(...)` from `lib_layered_config.generate`
takes the same arguments and returns an `ExamplesReport`: `.created` holds the files written,
`.kept` the existing ones left unchanged. A run that fails part-way (a full disk, a permission
wall) raises the original exception unchanged; `generated_before_failure(error)` (exported from
`lib_layered_config`) returns the example files it had already written, a `list[Path]`, for
either function.

**Display and logging.** `display_config(config, output_format=OutputFormat.HUMAN)` prints a config
section by section, each key under a `# layer:<layer> profile:<profile> (<path>)` comment and
TOML-quoted where it needs it (`OutputFormat.JSON` for plain JSON). The `read` command has its own
renderer, `# source: layer=<layer>, path=<path>` above each key, so one parser does not fit both;
both quote keys, headers and strings the same way, so a key named `"a.b"` reads back as one key.
`display_config` never wraps a line, so its human output parses as TOML at any width, piped or not.
`get_logger()` returns the stdlib `logging.Logger` named `lib_layered_config`; attach handlers to
it. Each record carries a `context` dict: always `record.context["trace_id"]`, plus the event's
own fields (often `layer` and `path`). `bind_trace_id("abc123")` sets that trace id for the current
context (a `ContextVar`); `read_config*` and `deploy_config` tag their events with it and leave it
bound, and with nothing bound the id is `None`. `i_should_fail()` raises a `RuntimeError` on
purpose, for testing failure paths.

## Common mistakes

| Mistake | Fix |
|---|---|
| Env prefix with a single/double underscore (`MY_APP_...`) | The prefix ends in a **triple** underscore: `MY_APP___`. Run `env-prefix`. |
| Forgetting the `defaults` layer or the `env`-wins ordering | Precedence is `defaults -> app -> host -> user -> dotenv -> env`. |
| Slugifying vendor/app for macOS/Windows paths | `vendor`/`app` are used verbatim (spaces kept). `slug` is never rewritten either: one with a space or other unsafe character is refused (`ValidationError`). Only the env prefix reshapes it (upper case, dashes to underscores). |
| Hunting for "why is this value X" by hand | Use `config.origin(key)` or `read-json` - provenance is built in. |
| Committing a `.env` with secrets | `.env` is for local secrets only; never commit it; keep mode `0o600`. |
| Writing `user_file = 640` (a TOML int is decimal) | Quote it: `user_file = "0o640"`; deploy refuses a bare integer and any group-writable, world-writable mode, or an execute bit on a file. |
| Reaching for `--no-permissions` when deploy refuses a broken config | Give both `--dir-mode` and `--file-mode`; `--no-permissions` leaves a secrets file to the umask. |
| Building `permissions=` from the application's `read_config(...)` to carry a `--set` | Pass `permission_overrides={"user_file": "0o640"}`: the application's read includes `.env` and the deployed files, which deploy leaves out on purpose. |

## Full detail

This skill is the self-contained agent guide; the repository docs are not shipped with the
installed package, so use these web links for exhaustive detail:

- Project (GitHub): https://github.com/bitranox/lib_layered_config
- Package (PyPI): https://pypi.org/project/lib-layered-config/
- README: https://github.com/bitranox/lib_layered_config/blob/master/README.md
- Identifiers, profiles, per-OS paths: https://github.com/bitranox/lib_layered_config/blob/master/docs/identifiers.md
- Configuration file structure: https://github.com/bitranox/lib_layered_config/blob/master/docs/config-file-structure.md
- CLI reference: https://github.com/bitranox/lib_layered_config/blob/master/docs/cli-reference.md
- Python API reference: https://github.com/bitranox/lib_layered_config/blob/master/docs/python-api.md

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.