API Reference

This reference provides a practical, browsable overview of PKonfig’s public API with direct links, short summaries, and detailed signatures. See Quickstart for a guided introduction and examples.

  • Core configuration container (Config) and validation workflow.

  • Typed fields and how they convert raw source values.

  • Storage backends for merging environment variables and config files.

  • Error types you can catch in your application.

See also

Tutorials — deep dives and step-by-step guides that expand on the API overview.

Core

Config

High-level configuration container. Subclass it and declare Field descriptors.

Key takeaways

  • Pass one or more storage backends in priority order (Env, Yaml, etc.).

  • Use alias="..." to namespace nested configs when composing large trees.

  • Leave fail_fast=True in production to surface validation errors during start-up.

Tip

Call cfg.check() if you instantiate a config with fail_fast=False and later want to validate all fields eagerly.

Nested configs

Nest Config subclasses as class attributes to create structured groups. Aliases cascade automatically so nested keys match the parent hierarchy when resolving values.

class pkonfig.config.Config(*storages, alias='', fail_fast=True, **kwargs)[source]

Bases: CachedBaseConfig

Base configuration container.

Define your configuration by subclassing Config and declaring Field descriptors (from pkonfig.fields) as class attributes or nested Configs for grouping.

Parameters:
  • *storages (BaseStorage) – One or more storage backends to read configuration values from, in priority order (leftmost has the highest priority).

  • alias (str, optional) – Optional alias for this config used to build nested keys, by default “”.

  • fail_fast (bool, optional) – If True (default), access all declared fields during initialization to ensure required values are present, and types/validators pass. If False, validation happens lazily on first access.

  • kwargs (dict, optional) – Keyword arguments transformed into a DictStorage

check()[source]

Eagerly access all declared fields to validate presence and types.

This will also recursively validate nested Configs. :raises ConfigError: If any required value is missing or fails type/validation in underlying fields.

Return type:

None

classmethod register_type_factory(python_type, factory)[source]
Parameters:
  • python_type (type[Any])

  • factory (Type[Field])

Return type:

None

get(item, default='NOT_SET')

Get item from storage or return default.

Parameters:
  • item (str)

  • default (Any)

Return type:

Any

internal_key(item)

Prepend an item with self._root_path.

Parameters:

item (str)

Return type:

Tuple[str, …]

set_alias(alias)

Set alias if it wasn’t already defined.

Parameters:

alias (str)

Return type:

None

set_root_path(root_path)

Set the root path prefix used to build full keys for nested configs.

Parameters:

root_path (Tuple[str, ...])

Return type:

None

set_storage(storage)

Set the storage ChainMap. Used internally when nesting configs.

Parameters:

storage (ChainMap)

Return type:

None

Usage example

from pkonfig import storage
from pkonfig.config import Config

class Database(Config):
    host: str = "localhost"
    port: int = 5432

class App(Config):
    debug: bool = False
    db: Database

cfg = App(storage.Env(prefix="APP"))
print(cfg.debug, cfg.db.port)

Errors

Common exceptions raised by PKonfig.

ConfigError : Base class for all configuration issues. Catch this if you want a single handler for every PKonfig error.

ConfigValueNotFoundError : Raised when a required key is missing across every storage you provided.

ConfigTypeError : Raised when a value exists but cannot be coerced into the field’s declared type.

exception pkonfig.errors.ConfigError[source]

Bases: Exception

Configuration error

exception pkonfig.errors.ConfigValueNotFoundError[source]

Bases: ConfigError

Failed to find value in a given storage (s)

exception pkonfig.errors.ConfigTypeError[source]

Bases: ConfigError

Value has the wrong type

exception pkonfig.errors.NullTypeError[source]

Bases: ConfigError

Non nullable value is None

Fields

Field descriptors define types, casting, and validation for config values.

Field : Base descriptor with shared validation hooks and metadata.

Bool : Parses truthy strings / integers (“true”, “1”) into bool.

Int : Casts numeric strings into int, validating bounds if specified.

Float : Converts values into floating-point numbers.

DecimalField : Preserves precision by returning Decimal instances.

Str : Returns raw string values (after optional trimming / defaults).

Byte : Produces immutable bytes blobs.

Bytes : Alias to Byte for readability.

ByteArray : Produces mutable bytearray instances.

PathField : Normalises paths into pathlib.Path objects.

File : Validates that the resolved path points to an existing file.

Folder : Validates that the resolved path points to an existing directory.

EnumField : Restricts values to members of a supplied Enum type.

LogLevel : Maps strings like “info”/”ERROR” into logging level integers.

Choice : Validates membership within a predefined set of allowed values.

ListField : Parse lists from strings or iterables. Useful for values like “a,b,c” or when storages return arrays. Use cast_function to convert each element:

from pkonfig import Config, DictStorage

class C(Config):
    tags: list[str]
    ids: list[int]

cfg = C(DictStorage(tags="a, b, c", ids="1,2,3"))
assert cfg.tags == ["a", "b", "c"]
assert cfg.ids == [1, 2, 3]

Tip

All field classes accept default, required, and optional validator hooks. Compose them to keep environment parsing declarative.

class pkonfig.fields.Field(default='NOT_SET', alias='', nullable=False)[source]

Bases: Generic[T], _Descriptor, ABC

Base config attribute descriptor.

Field is a data descriptor used as a class attribute of a Config subclass. On first access it retrieves a raw value from the attached storage, casts it to the target Python type and validates it. The result is cached a per-field key.

Parameters:
  • default (Any, optional) – Default value if the key is not found in storage. If left as NOT_SET, a ConfigValueNotFoundError will be raised on access. If the default is None, the field becomes nullable.

  • alias (str, optional) – Name to use in storage instead of the attribute name, by default “”.

  • nullable (bool, optional) – Whether None is accepted as a value, by default, False.

get(instance)[source]
Parameters:

instance (BaseConfig)

Return type:

T

abstract cast(value)[source]

Cast value to a Python type.

Parameters:

value (Any)

Return type:

T

validate(value)[source]

Implement this method to validate value

Parameters:

value (Any)

Return type:

None

Storage backends

Choose one or more storages and pass them to your Config. Leftmost storage has highest priority.

Storage

Best for

Notes

Env

Runtime overrides via os.environ

Optional prefix/delimiter helpers mirror Twelve-Factor style deployment.

DotEnv

Local developer overrides

Parses .env files with comment and prefix handling.

Ini

Legacy INI configuration

Exposes advanced configparser tuning knobs.

Json

Simple machine-generated settings

Uses json.load and preserves nested structures.

Toml

Modern app configs

Works with tomllib/tomli automatically.

Yaml

Verbose hierarchical configs

Uses yaml.safe_load; beware implicit type coercion.

Usage example

from pkonfig import storage
from pkonfig.config import Config
from pkonfig.fields import Str

class Service(Config):
    name = Str("api")

cfg = Service(
    storage.Env(prefix="SERVICE"),
    storage.Yaml("settings.yaml", missing_ok=True),
)
print(cfg.name)

Base protocol and concrete backends

This page shows a brief index. Follow the links in the overview to get detailed documentation for each storage backend and the BaseStorage protocol.