Skip to main content

darwin-config

English · 简体中文

A layered, recursive JSON / YAML / TOML configuration loader: declare where values come from, how they merge, how they are validated and referenced — all in one file. The library takes care of the rest.

  • Zero third-party dependencies in the core; JSON and TOML reading use the standard library, YAML is an optional extra
  • One DSL covers everything: layered imports, template merges, environment variables, in-file / cross-file references, arithmetic expressions, and schema validation
  • A small, well-defined API: load, read, override, alias, validate and trace — no redundant state-management helpers
  • Optional L1 framework adapters for Flask, Django and Pydantic — see section 6
pip install darwin-config              # JSON + TOML reading work out of the box
pip install 'darwin-config[yaml]'      # add YAML support
pip install 'darwin-config[toml]'      # add TOML *writing* (reading is built in)
pip install 'darwin-config[all]'       # all formats
pip install 'darwin-config[pydantic]'  # typed validation adapter (see section 6)

Python >= 3.12.


1. At a glance: what a config file looks like

The same configuration in equivalent JSON and YAML. Directives are bare keywords: import / merge / mount / schema:

settings.yaml

import:                          # 1) import base layers first; multiple allowed, later ones override earlier ones
  - base.yaml
schema:                          # 2) validate + fill defaults (port is missing below, so 5432 is filled in)
  database.host: { type: string, required: true }
  database.port: { type: integer, default: 5432, min: 1, max: 65535 }

database:
  host: ${DB_HOST:localhost}     # 3) environment variable: values > env > default
  # port is filled in by the schema
  dsn: "postgresql://${this.database.host}:${this.database.port}/app"  # 4) in-file reference
  pool:
    merge: ${this.defaults.pool} # 5) reuse another object in this file as a template
    max: 50

# Template object (not meant to be a standalone config; used only as a merge source)
defaults:
  pool: { min: 1, max: 10, timeout: 30 }

app:
  retry: 3
  interval: 2
  budget: "%{calc: ${this.app.retry} * ${this.app.interval} }"  # 6) arithmetic (quote it in YAML)
from darwin_config import init_config, get_config

init_config(files=["settings.yaml"], mount="config", validate=True)

get_config("config.database.dsn")   # 'postgresql://localhost:5432/app'
get_config("config.database.pool")  # {'min': 1, 'max': 50, 'timeout': 30}
get_config("config.app.budget")     # 6

Equivalent JSON (%{calc: ...} needs no quotes here):

{
  "import": ["base.json"],
  "schema": {
    "database.host": { "type": "string", "required": true },
    "database.port": { "type": "integer", "default": 5432, "min": 1, "max": 65535 }
  },
  "database": {
    "host": "${DB_HOST:localhost}",
    "dsn": "postgresql://${this.database.host}:${this.database.port}/app",
    "pool": { "merge": "${this.defaults.pool}", "max": 50 }
  },
  "defaults": { "pool": { "min": 1, "max": 10, "timeout": 30 } },
  "app": {
    "retry": 3,
    "interval": 2,
    "budget": "%{calc: ${this.app.retry} * ${this.app.interval} }"
  }
}

Equivalent TOML (root-level keys come before any [table]; ~ escapes must be quoted):

import = ["base.toml"]

[schema.database.host]
type = "string"
required = true

[schema.database.port]
type = "integer"
default = 5432

[defaults.pool]
min = 1
max = 10
timeout = 30

[database]
host = "${DB_HOST:localhost}"
dsn = "postgresql://${this.database.host}:${this.database.port}/app"

[database.pool]
merge = "${this.defaults.pool}"
max = 50

[app]
retry = 3
interval = 2
budget = "%{calc: ${this.app.retry} * ${this.app.interval} }"

examples/ contains 8 sets of equivalent JSON/YAML/TOML samples and a runnable demo. Run uv run --all-extras python examples/demo.py to see every capability in action.


2. Syntax quick reference

Syntax Meaning Resolved at
import: "base.yaml" / import: [...] Import other configs, resolved relative to the current file; nesting is supported. Later imports override earlier ones; the current file overrides all imports Load time
merge: ${this.templates.http} / [...] Deep-merge another object in the same file into the current one; the current object's fields win Load time
mount: adapter.tushare Declare the mount point of a file (top level only; used by add_config) Load time
schema: {...} / schema: "rules.json" Validation rules, inline or from an external file (top level only; external files may themselves use import) Load time, before env substitution
${this.a.b} In-file reference; references can chain Load time
${root.a.b} Global config-tree reference, works across files; resolved on read at runtime Runtime
${VAR} / ${VAR:default} Environment variable; precedence: values > os.environ > default; missing without a default raises an error Load time (any leftover at runtime is resolved once more by the node)
%{calc: expr} Restricted arithmetic; only + - * / // % ** and whitelisted functions (abs/min/max/round/sum/len/int/float/str/bool) Runtime
~import / ~schema, etc. The ~ prefix escapes a reserved word into an ordinary business field (unescaped at the end of the pipeline) Load time
{param} Business template placeholder, kept as-is and never touched by env substitution —

Two YAML gotchas (JSON and TOML do not have these):

  1. %{calc: ...} must be quoted: total: "%{calc: ${this.a} * 2}", otherwise : is treated as a mapping separator by YAML.
  2. ${...} inside a flow sequence must be quoted: merge: ["${this.tpl}"]. Written bare as [${this.tpl}], YAML treats { as the start of a mapping and parsing fails. Bare use in a plain scalar is safe: url: ${this.host}/v1.

Three TOML notes:

  1. Root-level keys must appear before any [table] header — in TOML, keys written after [schema] belong to that table, not the root.
  2. ~-escaped keys must be quoted: "~import" = [...] (TOML bare keys disallow ~).
  3. Native TOML dates/timestamps are supported as datetime/date in schema rules (type = "datetime"). TOML has no null; omit a key instead.

3. Five core APIs in practice

init_config(files, mount="", values=None, validate=False, base_dir=None, directives=None)

Initialize the global configuration system: expand globs, load files in order, merge them, and build the node tree. Every call resets all previous state.

from darwin_config import init_config

# Multiple files: later files override earlier ones; globs and ${VAR} path variables both work
init_config(
    files=["config/base.yaml", "config/env/${APP_ENV:dev}/*.json"],
    mount="config",                    # mount everything under config.*; empty means the root
    values={"APP_ENV": "prod"},        # injected variables, higher priority than env vars
    validate=True,                     # enable schema validation and default filling
    base_dir="config",                 # base directory for relative paths; defaults to cwd
    directives={"import": "cfg_import"},  # optional: rename a reserved word
)

get_config(path="", default=None, raise_on_not_found=False)

Read a value. A whole-string ${root.xxx} expression is resolved on read, so it can reference config added later.

from darwin_config import get_config, ConfigPathNotFoundError

get_config("config.database.host")                    # 'localhost'
get_config("config.database.timeout", default=30)     # fallback when missing
get_config("config.database")                         # whole subtree (dict)
get_config()                                          # all resolved config
get_config("config.missing", raise_on_not_found=True) # raises ConfigPathNotFoundError

set_config(path, value)

Runtime override, not written back to any file; the source is marked as user and config_trace() shows a timestamp. Note that reload_config() discards these overrides.

from darwin_config import set_config, get_config

set_config("config.database.host", "127.0.0.1")
assert get_config("config.database.host") == "127.0.0.1"

try_config(*paths, default=None)

Return the first non-None value in order — handy for fallback chains; missing-path errors are swallowed.

from darwin_config import try_config

timeout = try_config(
    "config.runtime.timeout",   # runtime override
    "config.server.timeout",    # file config
    "config.defaults.timeout",  # fallback
    default=30,
)

add_config(source, mount=None, values=None, validate=True)

Append config after initialization: source may be a path, a glob string, or a dict. The file's own mount directive determines the real mount point. If the passed mount differs from the one declared in the file, an alias is registered automatically — both paths are readable, and writes go to the same node.

from darwin_config import add_config, get_config, config_trace

add_config("adapters/tushare.yaml")                       # uses the file's mount: adapter.tushare
add_config("adapters/extra/*.json", mount="custom.tushare")  # alias -> adapter.tushare
add_config({"mount": "runtime.cache", "ttl": 60})        # pass a dict directly

assert get_config("adapter.tushare.auth.token") == get_config("custom.tushare.auth.token")
print(config_trace("adapter.tushare.auth.token"))        # trace the source file and mount point

add_alias(alias, target)

Give an existing path a semantic name, or a compatibility name during a migration. Reads and writes through the alias hit the target node. The target may not exist yet — it is resolved on read (same as ${root.xxx}).

from darwin_config import add_alias, init_config, get_config, set_config

init_config(files=["settings.yaml"], mount="config")
add_alias("primary", "config.database")

get_config("primary.host")       # same as config.database.host
set_config("primary.host", "x")  # the original path changes too

Other APIs: reload_config() (replays all add_config calls), get_meta(path), config_trace(path), get_trace_summary(), get_aliases() / has_alias(), ConfigLoader (an independent instance that avoids global state), Schema / FieldRule / create_schema / validate_config / validate_and_fill, and the exceptions ConfigError / ConfigValidationError / ConfigPathNotFoundError / ConfigCircularReferenceError / ConfigMountError — all importable directly from darwin_config.

Only the APIs developers actually use are exported at the top level; there are no no-op compatibility functions or environment-variable management helpers.


4. Features in detail

4.1 Aliases

Not "a copy of the value" but a jump pointer inside the node tree: reads and writes target the same node. Supports longest-prefix matching and cycle detection. Use get_aliases() / has_alias() to inspect existing aliases.

Two ways to create one:

init_config(files=["settings.yaml"], mount="config")

# 1) Explicit registration (recommended): give an existing path a semantic name
add_alias("primary", "adapter.tushare")

# 2) Implicit during mounting: a passed mount differing from the file's mount registers an alias
add_config("adapter.yaml", mount="custom.tushare")

get_config("primary.auth.token")      # same as adapter.tushare.auth.token
set_config("primary.auth.token", "x") # the original path becomes x as well

Aliases share the same duplicate-name check as add_config; a circular reference raises ConfigCircularReferenceError on read.

4.2 Schema validation and defaults

Supports type (string/integer/float/boolean/array/object, plus datetime/date for TOML values), required, default, choices, min/max, pattern, custom validators, and message. Rules can be inline or in an external JSON/YAML/TOML file (which may itself import other rule files). Validation failures raise ConfigValidationError, whose errors is a field-keyed dict.

from darwin_config import Schema, create_schema, validate_and_fill

schema = create_schema({
    "host": {"type": "string", "required": True},
    "port": {"type": "integer", "default": 8080, "min": 1, "max": 65535},
})
cfg = validate_and_fill({"host": "localhost"}, schema)
# {'host': 'localhost', 'port': 8080}

Note the pipeline order is schema → environment variables: if a field is written as "${PORT}" but the schema declares integer, validation sees a string and reports a type error. Use %{calc: ${PORT}} when strict typing is required, or declare the field as string in the schema.

4.3 References: this vs root

  • ${this.xxx} is an in-file reference, resolved at load time; references can chain (a -> b -> c) and can be embedded in the middle of a string.
  • ${root.xxx} is a global reference, resolved from the root node at runtime, so it can reference other files — even config appended later via add_config.
  • The two can be mixed without interference; circular references raise ConfigCircularReferenceError.

4.4 Environment variables

The library only consumes environment variables; it never modifies the caller's process environment. Reference them in config with ${VAR} / ${VAR:default}; for explicit injection use init_config(values={...}), which takes precedence over os.environ. The library provides no helpers for reading or writing environment variables.

init_config(files=["settings.yaml"], mount="config", values={"DB_HOST": "localhost"})

4.5 Source tracing

Every leaf node carries source / mount / timestamp / overrides metadata:

config_trace("config.database.host")
# config.database.host → settings.yaml (mount: config) (overridden by: runtime.json)
get_trace_summary()   # {'settings.yaml': 12, 'runtime.json': 3, 'user': 1}

4.6 Three ways around reserved-word collisions

import/merge/mount/schema are reserved words, but they won't get in the way of normal business fields:

  1. Scope: mount / schema are recognized only at the top level of a file; a nested database.schema: "public" is an ordinary field.
  2. Escaping: ~import: [1, 2] and ~schema: {name: mysql} are unescaped into ordinary fields at the end of the pipeline.
  3. Remapping: init_config(..., directives={"import": "cfg_import"}) renames a directive globally; the original import then becomes an ordinary field again.

4.7 Standalone loader

When you don't want process-level global state:

from darwin_config import ConfigLoader

loader = ConfigLoader(config_files=["a.yaml", "b.yaml"], mount="cfg", validate=True)
data = loader.load()          # {'cfg': {...}}, no global node tree involved

5. Recursive merge rules

There are three merge points in the library, all with consistent semantics: dicts merge recursively, non-dicts are overwritten, and the later writer wins.

5.1 The import directive — cross-file layering

app.yaml   import: [common.yaml]        ┐
common.yaml import: base.yaml           ├─ base first, then common, then app itself
base.yaml  {server: {host, port, timeout}} ┘

Result: server = {host: <base>, port: <common>, timeout: <app>} — only the keys that appear are overridden; the rest are inherited. Multiple import entries merge in array order (later overrides earlier); the current file's top-level fields override everything last. This happens recursively at any nesting level, so database: {import: "db.yaml"} works too.

5.2 The merge directive — in-file object templates

defaults: { timeout: 30, retry: 3, headers: { Accept: json } }
job:
  merge: ${this.defaults}
  timeout: 60
# -> {timeout: 60, retry: 3, headers: {Accept: json}}

A merge source may be a string or an array (multiple sources merged in order) and must be in ${this.xxx} form. A missing source only logs a warning. Source objects may themselves contain merge, which is expanded recursively first.

5.3 add_config / multiple files — node-tree merge

  • Leaf over leaf: the new value wins; the old source is recorded in overrides and the timestamp is updated
  • Leaf against branch: the branch wins (it is not flattened by a scalar)
  • Branch against branch: recursive key-by-key merge, keys that don't appear are retained
  • Alias nodes are skipped and never merged
  • Multiple add_config calls follow call order; later wins. set_config is the highest-priority runtime override

Overall precedence (low → high): imported files (left → right) → current file's own fields → schema defaults (fill gaps only) → later files in files → add_config additions → set_config runtime settings

None is a valid value and overrides the old one rather than being ignored; reload_config() rebuilds from files and replays all add_config calls, which clears set_config runtime overrides.


6. Framework integration (L1 adapters)

L1 adapters copy a config subtree into the framework at startup. They live in darwin_config.integrations.* — the core API stays unchanged and framework-free. Flask/Django adapters are duck-typed (no framework import required); only the Pydantic adapter needs pip install 'darwin-config[pydantic]'. Optional [flask] / [django] extras exist for IDE type resolution.

Flask — inject into app.config:

from flask import Flask
from darwin_config import init_config
from darwin_config.integrations.flask import apply_flask_config

init_config(["settings.yaml"])   # must happen before the app reads its config
app = Flask(__name__)
apply_flask_config(app)          # copies the "flask" subtree
# apply_flask_config(app, "service", prefix="flask_", uppercase=True)

Django — in settings.py, uppercase names only:

from darwin_config import init_config, get_config
from darwin_config.integrations.django import django_settings

init_config(["settings.yaml"])
globals().update(django_settings())   # reads "django"; drops lowercase keys
# django_settings(uppercase=True)     # or uppercase every key instead
LOGGING = get_config("logging")       # straight into logging.config.dictConfig

Pydantic / FastAPI — typed validation:

from pydantic import BaseModel
from darwin_config.integrations.pydantic import validate_with_pydantic

class Settings(BaseModel):
    name: str
    port: int

settings = validate_with_pydantic(Settings, "app")   # or source={"name": "..."}

Adapters inject a snapshot: later set_config() / add_config() calls do not update Flask or Django settings automatically. Re-run the adapter after reload_config() if you need to sync.


7. Tests

pip install -e '.[all,pydantic,test]'
# or with uv: uv run --all-extras python -m pytest tests -q
pytest tests -q

Tests are split into tests/unit/ (individual modules: utilities, node tree, Schema, processor, etc.) and tests/integration/ (multi-file layering, mixed formats, end-to-end API flows, framework adapters), plus feature-oriented regression tests.

8. License

MIT

Metadata

Release files for darwin-config 0.3.0

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

Source distribution (sdist)

Source distribution for darwin-config 0.3.0
File Size Uploaded Provenance Actions
darwin_config-0.3.0.tar.gz 26.9 kB Without provenance Details for darwin_config-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for darwin-config 0.3.0
File Interpreter ABI Platform Actions
darwin_config-0.3.0-py3-none-any.whl Python 3 none any Details for darwin_config-0.3.0-py3-none-any.whl

Total release size: 60.1 kB

Release files / darwin_config-0.3.0.tar.gz

Download URL darwin_config-0.3.0.tar.gz
Size 26.9 kB
Tags Source
SHA-256 checksum
How to use checksums
882151ee50fd6adb29c483ead1dd717f06e3f504767b492763682d1d9b102f86
BLAKE2b-256 checksum
How to use checksums
439fb22a5fbbe34dbbd55ce7022a67ea4aa300458dec818f8745b95ff691ad0c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / darwin_config-0.3.0-py3-none-any.whl

Download URL darwin_config-0.3.0-py3-none-any.whl
Size 33.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8e3bcbdae53e07dbe210d8061aded2db8b6f1b4ef581ccea96097a3a1a3f20b5
BLAKE2b-256 checksum
How to use checksums
35de0c554c7a482013c70f6fdd9308561dd498dcf510ec1a41ab1d6e089dfbe0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for darwin-config 0.3.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.

Release history Release notifications | RSS feed

This release

0.3.0 This release

2 release files No provenance

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