Metadata-Version: 2.4
Name: vcti-config
Version: 5.0.1
Summary: Type-safe environment variable decoding and configuration resolution for Python
Author: Visual Collaboration Technologies Inc.
License-Expression: LicenseRef-Proprietary
Project-URL: Homepage, https://github.com/vcollab/vcti-python-config
Project-URL: Repository, https://github.com/vcollab/vcti-python-config
Project-URL: Changelog, https://github.com/vcollab/vcti-python-config/blob/main/CHANGELOG.md
Keywords: configuration,environment-variables,config,env,settings,typed
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Operating System :: OS Independent
Classifier: Typing :: Typed
Requires-Python: <3.15,>=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pydantic>=2.7
Requires-Dist: vcti-enum>=1.1.0
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Requires-Dist: pytest-cov; extra == "test"
Provides-Extra: lint
Requires-Dist: ruff; extra == "lint"
Provides-Extra: typecheck
Requires-Dist: mypy; extra == "typecheck"
Dynamic: license-file

# vcti-config

Type-safe environment variable decoding and configuration resolution for Python.

## Overview

VCollab applications take their configuration from several places:
environment variables, values the application already holds, and defaults.
Without a shared layer every package reinvents how a setting is named in
each place, which place wins, and how problems are reported.

`vcti-config` separates what an application needs from where the values
come from. A **model** is a `Config` subclass, a frozen
[pydantic](https://docs.pydantic.dev/) model that states field names, types
and constraints. A **resolver** knows one source: `Env` reads environment
variables, `Values` holds values supplied by code. Resolvers are applied in
priority order to a **draft**, each filling only what is still missing, and
`build()` returns the validated config or reports every problem at once.

A model can contain other models: **sections** that are always present, and
**one_of** choices where one setting selects which of several shapes is
built (an LLM adapter, a deployment target).

---

## Installation

```bash
pip install vcti-config
```

### In `requirements.txt`

```
vcti-config>=5.0.1
```

### In `pyproject.toml` dependencies

```toml
dependencies = [
    "vcti-config>=5.0.1",
]
```

---

## Quick Start

### Declare a model and resolve it from the environment

```python
from pathlib import Path

from vcti.config import Config, Env, Field

class AppConfig(Config):
    debug: bool = False
    port: int = Field(default=8080, ge=1, le=65535)
    name: str = "myapp"
    data_dir: Path | None = None

config = AppConfig.resolve(Env(prefix="MYAPP_")).build()   # reads os.environ
config.debug   # bool, from MYAPP_DEBUG
config.port    # int,  from MYAPP_PORT
config.name    # str,  from MYAPP_NAME
```

A field with no default is required. The prefix belongs to the resolver,
not to the model, and is used exactly as written: a field's variable is the
prefix followed by the upper-cased field name, so the prefix includes its
own underscore.

### Combine sources in priority order

Resolvers are listed highest priority first. Each fills only what the ones
before it left missing; defaults apply last.

```python
from vcti.config import Values

env = {"MYAPP_PORT": "8081", "MYAPP_DEBUG": "true"}   # stands in for os.environ

draft = AppConfig.resolve(
    Values({"port": 9000}),                           # values the code already has
    Env(prefix="MYAPP_", source=env),
)
config = draft.build()
config.port        # 9000, from Values
config.debug       # True, from MYAPP_DEBUG
draft.sources()    # {"debug": "env", "port": "values", "name": "default", ...}
```

`Values` is how a test forces a setting, and how an application passes on
what its own command-line parser produced. `source` is anything with
`get(name) -> str | None`, so `os.environ` and a plain `dict` both work.

### Handle all errors at once

```python
from vcti.config import ConfigErrors

class StrictConfig(Config):
    host: str
    port: int = Field(ge=1, le=65535)

try:
    StrictConfig.resolve(Env(prefix="STRICT_", source={"STRICT_PORT": "70000"})).build()
except ConfigErrors as exc:
    for err in exc.errors:        # every problem, each with its source
        print(err)
# 'host' has no value and no default (looked for: env STRICT_HOST).
# 'port': Input should be less than or equal to 65535 ('70000' from env STRICT_PORT).
```

### Compose models: sections and one_of

```python
from enum import StrEnum
from typing import ClassVar

from vcti.config import SecretStr, one_of

class Adapter(StrEnum):
    CLAUDE_CODE = "claude-code"
    OPENAI = "openai"

class ClaudeCodeConfig(Config):
    KIND: ClassVar[Adapter] = Adapter.CLAUDE_CODE     # → MYAPP_CLAUDE_CODE__*
    model: str = "sonnet"

class OpenAiConfig(Config):
    KIND: ClassVar[Adapter] = Adapter.OPENAI          # → MYAPP_OPENAI__*
    api_key: SecretStr                                # masked on display
    model: str = "gpt-4o-mini"

class StorageConfig(Config):
    cache_dir: Path

class ServiceConfig(Config):
    storage: StorageConfig                            # a section → MYAPP_STORAGE__*
    adapter: ClaudeCodeConfig | OpenAiConfig = one_of(default_kind=Adapter.CLAUDE_CODE)

env = {
    "MYAPP_STORAGE__CACHE_DIR": "/var/cache",
    "MYAPP_ADAPTER": "OPENAI",                        # selects the branch
    "MYAPP_OPENAI__API_KEY": "sk-example",
}
config = ServiceConfig.resolve(Env(prefix="MYAPP_", source=env)).build()
config.storage.cache_dir     # Path
config.adapter.api_key       # SecretStr('**********')
config.adapter.KIND          # Adapter.OPENAI
```

- A **section** is a field annotated with another `Config` class.
- A **one_of** is a field annotated with a union of `Config` classes that
  each declare `KIND`. Its selector is read from the variable named for the
  field (`MYAPP_ADAPTER`) and matched against the enum's member names; only
  the selected branch is built, so an unset required field in another
  branch is not an error. `one_of(default_kind=...)` is optional and names
  the branch used when nothing selects one.
- Use `isinstance` or `match` on `config.adapter` to branch on the choice.

### Construct a config directly

A model is an ordinary pydantic model, so a test that knows every value
needs no resolver:

```python
config = AppConfig(port=9000, name="test")
```

### Decode, read and resolve standalone

```python
from vcti.config import MISSING, decode_int, get_str, resolve_value

decode_int("8080")                                # 8080
raw = get_str({"PORT": " 8081 "}, "PORT")         # "8081"; None if unset or blank
port = resolve_value(MISSING if raw is None else decode_int(raw), default=8080)

# MISSING, not None, is the skip sentinel, so None is a real value:
resolve_value(MISSING, "env", default="x")        # "env"
resolve_value(None, "env", default="x")           # None
```

---

## Resolvers

| Resolver | Source | Notes |
|---|---|---|
| `Env(prefix, ...)` | Environment variables, or any `ConfigSource` | Strings; pydantic converts them on `build()` |
| `Values(mapping)` | Values held in code | Flat path keys or nested mappings; `None` is a real value |

`Env` options:

| Option | Purpose |
|---|---|
| `source` | Where to read from; defaults to `os.environ` |
| `separator` | Joins nested names; defaults to `__` |
| `aliases` | Extra variable names for a path: `{"LEGACY_PORT": "port"}` |
| `exclude` | Paths that must not be supplied from this source |
| `parsers` | Custom string parsers by type: `{list[str]: split_commas}` |
| `path_parsers` | Custom string parsers for single paths: `{"tags": split_commas}`. Wins over a parser for the type |
| `unknown` | Whether a variable that starts with the prefix and matches no field is an `"error"` (the default with a prefix) or `"ignore"`d |

What `Env` does to a raw string before pydantic sees it:

- A blank value counts as unset.
- A `list[...]` or `dict[...]` field is parsed as JSON.
- A one_of's selector is decoded to its enum member, by member name, or with
  the enum's `vcti-enum` coder if it has one.
- A `bool` field accepts the spellings below, case-insensitively.

| True | False |
|---|---|
| `1`, `true`, `yes`, `on`, `enabled`, `t`, `y` | `0`, `false`, `no`, `off`, `disabled`, `f`, `n` |

---

## Public API

| Name | Purpose |
|------|---------|
| `Config` | Base class for a model; `Config.resolve(*resolvers)` starts a draft |
| `Field`, `SecretStr` | pydantic's own, re-exported |
| `one_of` | Declares the default branch of a one_of field |
| `Draft` | A config being resolved: `resolve`, `get`, `sources`, `build` |
| `Env`, `Values` | The shipped resolvers |
| `Resolver` | The protocol a custom resolver implements |
| `SchemaEntry`, `Invalid` | What a custom resolver reads and may store |
| `ConfigSource`, `get_str` | A look-up-by-name source, and a stripped read from one |
| `resolve_value`, `MISSING` | Standalone priority resolution and its "no value" sentinel |
| `decode_bool/int/float/str/path/json/secret/enum`, `make_bool_decoder` | Standalone `str -> T` decoders |
| `ConfigErrors` | Raised by `build()`; holds `MissingValueError`, `InvalidValueError`, `UnknownKeyError`, `CollisionError` |
| `ConfigError`, `DecodeError` | The base class, and the error the standalone decoders raise |

---

## Dependencies

- [`pydantic`](https://docs.pydantic.dev/)
- [`vcti-enum`](https://github.com/vcollab/vcti-python-enum)

---

## Documentation

| If you want to… | Read |
|---|---|
| Get started using the package | [Quick Start](#quick-start) above |
| Understand the model, resolvers and draft, and the design decisions | [docs/design.md](docs/design.md) |
| Navigate and understand the source | [docs/source-guide.md](docs/source-guide.md) |
| Write a resolver for another source | [docs/extending.md](docs/extending.md) |
