Skip to content

liblaf.conf

Typed configuration primitives with environment loading and scoped overrides.

The public API is intentionally small:

The field_* helpers create Field descriptors with ready-made converters for booleans, numbers, JSON payloads, paths, lists, and temporal values.

Modules:

  • converters

    Expose converter helpers used by liblaf.conf fields and variables.

Type Aliases:

Classes:

  • BaseConfig

    Base class for descriptor-backed configuration containers.

  • ConfigMeta

    Collect config descriptors and cache one instance per config class.

  • Field

    Descriptor that declares one configuration value.

  • Group

    Descriptor that lazily attaches a nested object to a config instance.

  • Var

    Context-local storage for one configuration value.

Functions:

  • field

    Create a Field descriptor.

  • field_bool

    Create a field that parses booleans with Pydantic string rules.

  • field_date

    Create a field that parses calendar dates from strings.

  • field_datetime

    Create a field that parses datetimes from strings.

  • field_decimal

    Create a field that converts strings to Decimal.

  • field_float

    Create a field that converts strings to float values.

  • field_int

    Create a field that converts strings to int values.

  • field_json

    Create a field that decodes JSON strings.

  • field_list_str

    Create a field that splits strings into trimmed string lists.

  • field_path

    Create a field that normalizes values to Path.

  • field_str

    Create a field that keeps string values unchanged.

  • field_time

    Create a field that parses times from strings.

  • field_timedelta

    Create a field that parses duration strings to timedeltas.

  • group

    Create a Group descriptor.

Attributes:

__commit_id__ module-attribute

__commit_id__: str | None = None

__version__ module-attribute

__version__: str = '0.1.2'

__version_tuple__ module-attribute

__version_tuple__: tuple[int | str, ...] = (0, 1, 2)

Converter

Converter[T] = Callable[[str], T]

Factory

Factory[T] = Callable[[], T]

BaseConfig

Base class for descriptor-backed configuration containers.

Subclasses declare Field descriptors for individual settings and group descriptors for nested BaseConfig sections. Each config subclass is a cached singleton, while its bound Var values remain context-local.

Methods:

  • load_env

    Refresh all fields from their configured environment variables.

  • override

    Temporarily override fields or nested groups in the active context.

  • set

    Set fields or nested groups from Python values.

  • to_dict

    Serialize the active config tree to nested dictionaries.

  • to_namespace

    Serialize the active config tree to nested namespaces.

Attributes:

env_prefix class-attribute

env_prefix: str

name class-attribute

name: str

load_env

load_env() -> None

Refresh all fields from their configured environment variables.

Nested BaseConfig groups are refreshed recursively.

Source code in src/liblaf/conf/_config.py
def load_env(self) -> None:
    """Refresh all fields from their configured environment variables.

    Nested [`BaseConfig`][liblaf.conf.BaseConfig] groups are refreshed
    recursively.
    """
    for name in self._fields:
        var: Var[Any] = self._get_field(name)
        var.load_env()
    for name in self._groups:
        group: BaseConfig = self._get_group(name)
        group.load_env()

override

override(
    changes: Mapping[str, Any] | None = None,
    /,
    **kwargs: Any,
) -> Generator[None]

Temporarily override fields or nested groups in the active context.

Mapping values passed for nested groups are delegated to the nested config's own override() method. Previous values are restored even when the block exits with an exception.

Parameters:

  • changes (Mapping[str, Any] | None, default: None ) –

    Optional mapping of names to temporary values.

  • **kwargs (Any, default: {} ) –

    Additional name-to-value overrides.

Yields:

  • Generator[None]

    None while the overrides are active. Previous values are restored

  • Generator[None]

    when the context exits.

Source code in src/liblaf/conf/_config.py
@contextlib.contextmanager
def override(
    self, changes: Mapping[str, Any] | None = None, /, **kwargs: Any
) -> Generator[None]:
    """Temporarily override fields or nested groups in the active context.

    Mapping values passed for nested groups are delegated to the nested
    config's own `override()` method. Previous values are restored even when
    the block exits with an exception.

    Args:
        changes: Optional mapping of names to temporary values.
        **kwargs: Additional name-to-value overrides.

    Yields:
        `None` while the overrides are active. Previous values are restored
        when the context exits.
    """
    if changes is not None:
        kwargs.update(changes)
    with contextlib.ExitStack() as stack:
        for name, value in kwargs.items():
            var: BaseConfig | Var[Any] = self._get_field_or_group(name)
            stack.enter_context(var.override(value))
        yield

set

set(
    changes: Mapping[str, Any] | None = None,
    /,
    **kwargs: Any,
) -> None

Set fields or nested groups from Python values.

Mapping values passed for nested config groups are forwarded to that group's own set() method. When changes and keyword arguments contain the same name, the value from changes is applied.

Parameters:

  • changes (Mapping[str, Any] | None, default: None ) –

    Optional mapping of field or group names to new values.

  • **kwargs (Any, default: {} ) –

    Additional field or group updates.

Source code in src/liblaf/conf/_config.py
def set(self, changes: Mapping[str, Any] | None = None, /, **kwargs: Any) -> None:
    """Set fields or nested groups from Python values.

    Mapping values passed for nested config groups are forwarded to that
    group's own `set()` method. When `changes` and keyword arguments contain
    the same name, the value from `changes` is applied.

    Args:
        changes: Optional mapping of field or group names to new values.
        **kwargs: Additional field or group updates.
    """
    if changes is not None:
        kwargs.update(changes)
    for name, value in kwargs.items():
        var: BaseConfig | Var[Any] = self._get_field_or_group(name)
        var.set(value)

to_dict

to_dict() -> dict[str, Any]

Serialize the active config tree to nested dictionaries.

Returns:

  • dict[str, Any]

    A dictionary containing current field values and nested group

  • dict[str, Any]

    dictionaries.

Source code in src/liblaf/conf/_config.py
def to_dict(self) -> dict[str, Any]:
    """Serialize the active config tree to nested dictionaries.

    Returns:
        A dictionary containing current field values and nested group
        dictionaries.
    """
    result: dict[str, Any] = {}
    for name in self._fields:
        result[name] = self._get_field(name).get()
    for name in self._groups:
        result[name] = self._get_group(name).to_dict()
    return result

to_namespace

to_namespace() -> SimpleNamespace

Serialize the active config tree to nested namespaces.

Returns:

Source code in src/liblaf/conf/_config.py
def to_namespace(self) -> types.SimpleNamespace:
    """Serialize the active config tree to nested namespaces.

    Returns:
        A [`types.SimpleNamespace`][] tree mirroring
        [`to_dict()`][liblaf.conf.BaseConfig.to_dict].
    """
    result: types.SimpleNamespace = types.SimpleNamespace()
    for name in self._fields:
        setattr(result, name, self._get_field(name).get())
    for name in self._groups:
        setattr(result, name, self._get_group(name).to_namespace())
    return result

ConfigMeta

Bases: type


              flowchart TD
              liblaf.conf.ConfigMeta[ConfigMeta]

              

              click liblaf.conf.ConfigMeta href "" "liblaf.conf.ConfigMeta"
            

Collect config descriptors and cache one instance per config class.

Methods:

  • __call__

    Return the class singleton, creating it on first access.

  • __new__

    Create a config class with derived names and descriptor maps.

__call__

__call__[T: BaseConfig](*args, **kwargs) -> T

Return the class singleton, creating it on first access.

Source code in src/liblaf/conf/_config.py
def __call__[T: BaseConfig](cls: type[T], *args, **kwargs) -> T:
    """Return the class singleton, creating it on first access."""
    instance: T | None = cls.__dict__.get("_instance")
    if instance is None:
        instance = super().__call__(*args, **kwargs)
        cls._instance = instance
    return instance

__new__

__new__(
    mcs,
    name: str,
    bases: tuple[type, ...],
    namespace: dict[str, Any],
    /,
    **_kwargs: Any,
) -> type

Create a config class with derived names and descriptor maps.

Source code in src/liblaf/conf/_config.py
def __new__(
    mcs,
    name: str,
    bases: tuple[type, ...],
    namespace: dict[str, Any],
    /,
    **_kwargs: Any,
) -> type:
    """Create a config class with derived names and descriptor maps."""
    if "name" not in namespace:
        namespace["name"] = alias_generators.to_snake(name).removesuffix("_config")
    if "env_prefix" not in namespace:
        namespace["env_prefix"] = namespace["name"].upper() + "_"
    cls: type[BaseConfig] = cast(
        "type[BaseConfig]", super().__new__(mcs, name, bases, namespace)
    )
    fields: dict[str, Field[Any]] = {}
    groups: dict[str, Group[Any]] = {}
    for base in reversed(cls.__mro__[1:]):
        fields.update(getattr(base, "_fields", {}))
        groups.update(getattr(base, "_groups", {}))
    for key, value in namespace.items():
        match value:
            case Field():
                groups.pop(key, None)
                fields[key] = value
            case Group():
                fields.pop(key, None)
                groups[key] = value
            case _:
                fields.pop(key, None)
                groups.pop(key, None)
    cls._fields = fields
    cls._groups = groups
    return cls

Field dataclass

Field(
    env: str | None = None,
    default: T | MissingType = MISSING,
    factory: Factory[T] | None = None,
    converter: Converter[T] = identity,
)

Descriptor that declares one configuration value.

A Field stores the environment-variable name, default or factory, and converter used to create a bound Var. Binding is lazy: the Var is created the first time the field is accessed on a config instance.

Parameters:

  • env (str | None, default: None ) –
  • default (T | MissingType, default: <MissingType.MISSING: 1> ) –
  • factory (T | None, default: None ) –
  • converter (T, default: <function identity at 0x71bd62842610> ) –

Attributes:

Methods:

  • __get__

    Return this descriptor on classes or a cached bound Var on objects.

  • __set_name__

    Record the field name assigned by the owning config class.

converter class-attribute instance-attribute

converter: Converter[T] = identity

default class-attribute instance-attribute

default: T | MissingType = MISSING

env class-attribute instance-attribute

env: str | None = None

factory class-attribute instance-attribute

factory: Factory[T] | None = None

name class-attribute instance-attribute

name: str = field(init=False)

__get__

__get__(instance: None, owner: type | None = None) -> Self
__get__(
    instance: object, owner: type | None = None
) -> Var[T]

Return this descriptor on classes or a cached bound Var on objects.

Source code in src/liblaf/conf/_field.py
def __get__(
    self, instance: ConfigProtocol | None, owner: type | None = None
) -> Self | Var[T]:
    """Return this descriptor on classes or a cached bound `Var` on objects."""
    if instance is None:
        return self
    if self.name not in instance.__dict__:
        instance.__dict__[self.name] = self._bind(instance)
    return instance.__dict__[self.name]

__set_name__

__set_name__(owner: type, name: str) -> None

Record the field name assigned by the owning config class.

Source code in src/liblaf/conf/_field.py
def __set_name__(self, owner: type, name: str) -> None:
    """Record the field name assigned by the owning config class."""
    object.__setattr__(self, "name", name)

Group dataclass

Group(factory: Callable[[], T])

Descriptor that lazily attaches a nested object to a config instance.

BaseConfig helpers such as set(), load_env(), and to_dict() expect group values to be nested BaseConfig objects. The descriptor itself can cache any zero-argument factory result.

Parameters:

Attributes:

Methods:

  • __get__

    Return this descriptor on classes or a cached group value on objects.

  • __set_name__

    Record the group name assigned by the owning config class.

factory instance-attribute

factory: Callable[[], T]

name class-attribute instance-attribute

name: str = field(init=False)

__get__

__get__(instance: None, owner: type | None = None) -> Self
__get__(instance: object, owner: type | None = None) -> T

Return this descriptor on classes or a cached group value on objects.

Source code in src/liblaf/conf/_group.py
def __get__(self, instance: object | None, owner: type | None = None) -> Self | T:
    """Return this descriptor on classes or a cached group value on objects."""
    if instance is None:
        return self
    if self.name not in instance.__dict__:
        instance.__dict__[self.name] = self.factory()
    return instance.__dict__[self.name]

__set_name__

__set_name__(owner: type, name: str) -> None

Record the group name assigned by the owning config class.

Source code in src/liblaf/conf/_group.py
def __set_name__(self, owner: type, name: str) -> None:
    """Record the group name assigned by the owning config class."""
    object.__setattr__(self, "name", name)

Var dataclass

Var(
    name: str,
    default: T | MissingType = MISSING,
    factory: Factory[T] | None = None,
    env: str | None = None,
    converter: Converter[T] | None = None,
)

Context-local storage for one configuration value.

A Var can be seeded from an environment variable, a default value, or a factory. The active value is stored in a contextvars.ContextVar, so temporary overrides follow normal context propagation rules.

Parameters:

  • env (str | None) –
  • converter (T) –

Parameters:

  • name (str) –

    Name assigned to the underlying contextvars.ContextVar.

  • default (T | MissingType, default: MISSING ) –

    Default value used when env is unset.

  • factory (Factory[T] | None, default: None ) –

    Zero-argument callable used to create a default when default is omitted.

  • env (str | None, default: None ) –

    Environment-variable name to read during initialization and later load_env() calls.

  • converter (Converter[T] | None, default: None ) –

    Callable used to convert environment strings to Python values. Defaults to identity.

Methods:

  • __hash__

    Return the hash of the wrapped context variable.

  • get

    Return the active value.

  • load_env

    Reload the active value from the configured environment variable.

  • override

    Temporarily set a value in the active context.

  • reset

    Restore a value captured by set().

  • set

    Set the active value.

Attributes:

Source code in src/liblaf/conf/_var.py
def __init__(
    self,
    name: str,
    default: T | MissingType = MISSING,
    factory: Factory[T] | None = None,
    env: str | None = None,
    converter: Converter[T] | None = None,
) -> None:
    """Create a context-local config variable.

    Args:
        name: Name assigned to the underlying
            [`contextvars.ContextVar`][].
        default: Default value used when `env` is unset.
        factory: Zero-argument callable used to create a default when
            `default` is omitted.
        env: Environment-variable name to read during initialization and
            later `load_env()` calls.
        converter: Callable used to convert environment strings to Python
            values. Defaults to [`identity`][liblaf.conf.converters.identity].
    """
    if converter is None:
        converter: Converter[T] = converters.identity
    if env is not None:
        value: str | None = os.getenv(env)
        if value is not None:
            default: T = cast("T", converter(value))
    if default is MISSING and factory is not None:
        default: T = factory()
    if default is MISSING:
        var: contextvars.ContextVar[T] = contextvars.ContextVar(name)
    else:
        var: contextvars.ContextVar[T] = contextvars.ContextVar(
            name, default=default
        )
    object.__setattr__(self, "_var", var)
    object.__setattr__(self, "env", env)
    object.__setattr__(self, "converter", converter)

converter instance-attribute

converter: Converter[T]

env instance-attribute

env: str | None

name property

name: str

Name of the wrapped contextvars.ContextVar.

__hash__

__hash__() -> int

Return the hash of the wrapped context variable.

Source code in src/liblaf/conf/_var.py
def __hash__(self) -> int:
    """Return the hash of the wrapped context variable."""
    return hash(self._var)

get

get() -> T
get(default: T) -> T
get[D](default: D) -> D | T

Return the active value.

Parameters:

  • default (Any, default: MISSING ) –

    Optional fallback returned when the variable has no value.

Returns:

  • T

    The active context value, or default when provided and no value is

  • T

    set.

Source code in src/liblaf/conf/_var.py
def get(self, default: Any = MISSING) -> T:
    """Return the active value.

    Args:
        default: Optional fallback returned when the variable has no value.

    Returns:
        The active context value, or `default` when provided and no value is
        set.
    """
    if default is MISSING:
        return self._var.get()
    return self._var.get(default)

load_env

load_env() -> None

Reload the active value from the configured environment variable.

Source code in src/liblaf/conf/_var.py
def load_env(self) -> None:
    """Reload the active value from the configured environment variable."""
    if self.env is None:
        return
    value: str | None = os.getenv(self.env)
    if value is None:
        return
    if self.converter is None:
        self.set(cast("T", value))
    else:
        self.set(self.converter(value))

override

override(value: T) -> Generator[None]

Temporarily set a value in the active context.

Parameters:

  • value (T) –

    Temporary value to expose inside the context.

Yields:

  • Generator[None]

    None while the override is active. The previous value is restored

  • Generator[None]

    when the context exits.

Source code in src/liblaf/conf/_var.py
@contextlib.contextmanager
def override(self, value: T) -> Generator[None]:
    """Temporarily set a value in the active context.

    Args:
        value: Temporary value to expose inside the context.

    Yields:
        `None` while the override is active. The previous value is restored
        when the context exits.
    """
    token: contextvars.Token[T] = self._var.set(value)
    try:
        yield
    finally:
        self._var.reset(token)

reset

reset(token: Token[T]) -> None

Restore a value captured by set().

Parameters:

  • token (Token[T]) –

    Token returned by a previous set() call.

Source code in src/liblaf/conf/_var.py
def reset(self, token: contextvars.Token[T]) -> None:
    """Restore a value captured by [`set()`][liblaf.conf.Var.set].

    Args:
        token: Token returned by a previous `set()` call.
    """
    self._var.reset(token)

set

set(value: T) -> Token[T]

Set the active value.

Parameters:

  • value (T) –

    New value for the active context.

Returns:

Source code in src/liblaf/conf/_var.py
def set(self, value: T) -> contextvars.Token[T]:
    """Set the active value.

    Args:
        value: New value for the active context.

    Returns:
        A [`contextvars.Token`][] that can restore the previous value with
        [`reset()`][liblaf.conf.Var.reset].
    """
    return self._var.set(value)

field

field[T](
    *,
    env: str | None = None,
    default: T | MissingType = MISSING,
    factory: Factory[T] | None = None,
    converter: Converter[T] = identity,
) -> Field[T]

Create a Field descriptor.

Parameters:

  • env (str | None, default: None ) –

    Explicit environment-variable name. When omitted, the owning config's env_prefix and the field name are combined.

  • default (T | MissingType, default: MISSING ) –

    Default value used when no environment value is present.

  • factory (Factory[T] | None, default: None ) –

    Zero-argument callable used to create a default when default is omitted.

  • converter (Converter[T], default: identity ) –

    Callable used to convert environment strings to Python values.

Returns:

Source code in src/liblaf/conf/_field.py
def field[T](
    *,
    env: str | None = None,
    default: T | MissingType = MISSING,
    factory: Factory[T] | None = None,
    converter: Converter[T] = converters.identity,
) -> Field[T]:
    """Create a [`Field`][liblaf.conf.Field] descriptor.

    Args:
        env: Explicit environment-variable name. When omitted, the owning
            config's `env_prefix` and the field name are combined.
        default: Default value used when no environment value is present.
        factory: Zero-argument callable used to create a default when `default`
            is omitted.
        converter: Callable used to convert environment strings to Python
            values.

    Returns:
        A field descriptor ready to assign on a
        [`BaseConfig`][liblaf.conf.BaseConfig] subclass.
    """
    return Field(env=env, default=default, factory=factory, converter=converter)

field_bool

field_bool(
    env: str | None = None,
    default: bool | MissingType = MISSING,
    factory: Factory[bool] | None = None,
    converter: Converter[bool] | None = None,
) -> Field[bool]

Create a field that parses booleans with Pydantic string rules.

Parameters:

  • env (str | None, default: None ) –

    Explicit environment-variable name.

  • default (bool | MissingType, default: MISSING ) –

    Default boolean value.

  • factory (Factory[bool] | None, default: None ) –

    Zero-argument callable used when default is omitted.

  • converter (Converter[bool] | None, default: None ) –

    Optional custom converter. When omitted, Pydantic string validation is used.

Returns:

Source code in src/liblaf/conf/_field_specifiers.py
def field_bool(
    env: str | None = None,
    default: bool | MissingType = MISSING,  # noqa: FBT001
    factory: Factory[bool] | None = None,
    converter: Converter[bool] | None = None,
) -> Field[bool]:
    """Create a field that parses booleans with Pydantic string rules.

    Args:
        env: Explicit environment-variable name.
        default: Default boolean value.
        factory: Zero-argument callable used when `default` is omitted.
        converter: Optional custom converter. When omitted, Pydantic string
            validation is used.

    Returns:
        A [`Field`][liblaf.conf.Field] whose converter returns `bool` values.
    """
    if converter is None:
        converter: Converter[bool] = converters.pydantic_type_adapter_validate_strings(
            bool
        )
    return Field(env=env, default=default, factory=factory, converter=converter)

field_date

field_date(
    env: str | None = None,
    default: Any | MissingType = MISSING,
    factory: Factory[Any] | None = None,
    converter: Converter[Any] | None = None,
) -> Field[Any]

Create a field that parses calendar dates from strings.

Parameters:

  • env (str | None, default: None ) –

    Explicit environment-variable name.

  • default (Any | MissingType, default: MISSING ) –

    Default date-like value.

  • factory (Factory[Any] | None, default: None ) –

    Zero-argument callable used when default is omitted.

  • converter (Converter[Any] | None, default: None ) –

    Optional custom converter. When omitted, Pydantic's pendulum Date adapter is used.

Returns:

Source code in src/liblaf/conf/_field_specifiers.py
def field_date(
    env: str | None = None,
    default: Any | MissingType = MISSING,
    factory: Factory[Any] | None = None,
    converter: Converter[Any] | None = None,
) -> Field[Any]:
    """Create a field that parses calendar dates from strings.

    Args:
        env: Explicit environment-variable name.
        default: Default date-like value.
        factory: Zero-argument callable used when `default` is omitted.
        converter: Optional custom converter. When omitted, Pydantic's
            pendulum `Date` adapter is used.

    Returns:
        A [`Field`][liblaf.conf.Field] whose default converter returns date
        values.
    """
    if converter is None:
        converter: Converter[datetime.date] = (
            converters.pydantic_type_adapter_validate_strings(Date)
        )
    return Field(env=env, default=default, factory=factory, converter=converter)

field_datetime

field_datetime(
    env: str | None = None,
    default: datetime | MissingType = MISSING,
    factory: Factory[datetime] | None = None,
    converter: Converter[datetime] | None = None,
) -> Field[datetime]

Create a field that parses datetimes from strings.

Parameters:

  • env (str | None, default: None ) –

    Explicit environment-variable name.

  • default (datetime | MissingType, default: MISSING ) –

    Default datetime value.

  • factory (Factory[datetime] | None, default: None ) –

    Zero-argument callable used when default is omitted.

  • converter (Converter[datetime] | None, default: None ) –

    Optional custom converter. When omitted, Pydantic's pendulum DateTime adapter is used.

Returns:

Source code in src/liblaf/conf/_field_specifiers.py
def field_datetime(
    env: str | None = None,
    default: datetime.datetime | MissingType = MISSING,
    factory: Factory[datetime.datetime] | None = None,
    converter: Converter[datetime.datetime] | None = None,
) -> Field[datetime.datetime]:
    """Create a field that parses datetimes from strings.

    Args:
        env: Explicit environment-variable name.
        default: Default datetime value.
        factory: Zero-argument callable used when `default` is omitted.
        converter: Optional custom converter. When omitted, Pydantic's
            pendulum `DateTime` adapter is used.

    Returns:
        A [`Field`][liblaf.conf.Field] whose converter returns
        [`datetime.datetime`][] values.
    """
    if converter is None:
        converter: Converter[datetime.datetime] = (
            converters.pydantic_type_adapter_validate_strings(DateTime)
        )
    return Field(env=env, default=default, factory=factory, converter=converter)

field_decimal

field_decimal(
    env: str | None = None,
    default: Decimal | MissingType = MISSING,
    factory: Factory[Decimal] | None = None,
    converter: Converter[Decimal] | None = None,
) -> Field[Decimal]

Create a field that converts strings to Decimal.

Parameters:

  • env (str | None, default: None ) –

    Explicit environment-variable name.

  • default (Decimal | MissingType, default: MISSING ) –

    Default decimal value.

  • factory (Factory[Decimal] | None, default: None ) –

    Zero-argument callable used when default is omitted.

  • converter (Converter[Decimal] | None, default: None ) –

    Optional custom converter. When omitted, Decimal is used.

Returns:

Source code in src/liblaf/conf/_field_specifiers.py
def field_decimal(
    env: str | None = None,
    default: Decimal | MissingType = MISSING,
    factory: Factory[Decimal] | None = None,
    converter: Converter[Decimal] | None = None,
) -> Field[Decimal]:
    """Create a field that converts strings to [`Decimal`][decimal.Decimal].

    Args:
        env: Explicit environment-variable name.
        default: Default decimal value.
        factory: Zero-argument callable used when `default` is omitted.
        converter: Optional custom converter. When omitted,
            [`Decimal`][decimal.Decimal] is used.

    Returns:
        A [`Field`][liblaf.conf.Field] whose converter returns decimal values.
    """
    if converter is None:
        converter: Converter[Decimal] = Decimal
    return Field(env=env, default=default, factory=factory, converter=converter)

field_float

field_float(
    env: str | None = None,
    default: float | MissingType = MISSING,
    factory: Factory[float] | None = None,
    converter: Converter[float] | None = None,
) -> Field[float]

Create a field that converts strings to float values.

Parameters:

  • env (str | None, default: None ) –

    Explicit environment-variable name.

  • default (float | MissingType, default: MISSING ) –

    Default float value.

  • factory (Factory[float] | None, default: None ) –

    Zero-argument callable used when default is omitted.

  • converter (Converter[float] | None, default: None ) –

    Optional custom converter. When omitted, float is used.

Returns:

Source code in src/liblaf/conf/_field_specifiers.py
def field_float(
    env: str | None = None,
    default: float | MissingType = MISSING,
    factory: Factory[float] | None = None,
    converter: Converter[float] | None = None,
) -> Field[float]:
    """Create a field that converts strings to `float` values.

    Args:
        env: Explicit environment-variable name.
        default: Default float value.
        factory: Zero-argument callable used when `default` is omitted.
        converter: Optional custom converter. When omitted, `float` is used.

    Returns:
        A [`Field`][liblaf.conf.Field] whose converter returns `float` values.
    """
    if converter is None:
        converter: Converter[float] = float
    return Field(env=env, default=default, factory=factory, converter=converter)

field_int

field_int(
    env: str | None = None,
    default: int | MissingType = MISSING,
    factory: Factory[int] | None = None,
    converter: Converter[int] | None = None,
) -> Field[int]

Create a field that converts strings to int values.

Parameters:

  • env (str | None, default: None ) –

    Explicit environment-variable name.

  • default (int | MissingType, default: MISSING ) –

    Default integer value.

  • factory (Factory[int] | None, default: None ) –

    Zero-argument callable used when default is omitted.

  • converter (Converter[int] | None, default: None ) –

    Optional custom converter. When omitted, int is used.

Returns:

Source code in src/liblaf/conf/_field_specifiers.py
def field_int(
    env: str | None = None,
    default: int | MissingType = MISSING,
    factory: Factory[int] | None = None,
    converter: Converter[int] | None = None,
) -> Field[int]:
    """Create a field that converts strings to `int` values.

    Args:
        env: Explicit environment-variable name.
        default: Default integer value.
        factory: Zero-argument callable used when `default` is omitted.
        converter: Optional custom converter. When omitted, `int` is used.

    Returns:
        A [`Field`][liblaf.conf.Field] whose converter returns `int` values.
    """
    if converter is None:
        converter: Converter[int] = int
    return Field(env=env, default=default, factory=factory, converter=converter)

field_json

field_json(
    env: str | None = None,
    default: Any | MissingType = MISSING,
    factory: Factory[Any] | None = None,
    converter: Converter[Any] | None = None,
) -> Field[Any]

Create a field that decodes JSON strings.

Parameters:

  • env (str | None, default: None ) –

    Explicit environment-variable name.

  • default (Any | MissingType, default: MISSING ) –

    Default JSON-compatible value.

  • factory (Factory[Any] | None, default: None ) –

    Zero-argument callable used when default is omitted.

  • converter (Converter[Any] | None, default: None ) –

    Optional custom converter. When omitted, json.loads is used.

Returns:

Source code in src/liblaf/conf/_field_specifiers.py
def field_json(
    env: str | None = None,
    default: Any | MissingType = MISSING,
    factory: Factory[Any] | None = None,
    converter: Converter[Any] | None = None,
) -> Field[Any]:
    """Create a field that decodes JSON strings.

    Args:
        env: Explicit environment-variable name.
        default: Default JSON-compatible value.
        factory: Zero-argument callable used when `default` is omitted.
        converter: Optional custom converter. When omitted,
            [`json.loads`][] is used.

    Returns:
        A [`Field`][liblaf.conf.Field] whose converter returns decoded JSON
        values.
    """
    if converter is None:
        converter: Converter[Any] = json.loads
    return Field(env=env, default=default, factory=factory, converter=converter)

field_list_str

field_list_str(
    env: str | None = None,
    default: list[str] | MissingType = MISSING,
    factory: Factory[list[str]] | None = None,
    converter: Converter[list[str]] | None = None,
    delimiter: str = ",",
) -> Field[list[str]]

Create a field that splits strings into trimmed string lists.

Empty items are preserved. For example, the default converter turns "a,, b," into ["a", "", "b", ""].

Parameters:

  • env (str | None, default: None ) –

    Explicit environment variable name.

  • default (list[str] | MissingType, default: MISSING ) –

    Default list value.

  • factory (Factory[list[str]] | None, default: None ) –

    Callable that produces a fresh default list.

  • converter (Converter[list[str]] | None, default: None ) –

    Optional converter overriding the built-in splitter.

  • delimiter (str, default: ',' ) –

    Delimiter used by the default converter.

Returns:

Source code in src/liblaf/conf/_field_specifiers.py
def field_list_str(
    env: str | None = None,
    default: list[str] | MissingType = MISSING,
    factory: Factory[list[str]] | None = None,
    converter: Converter[list[str]] | None = None,
    delimiter: str = ",",
) -> Field[list[str]]:
    """Create a field that splits strings into trimmed string lists.

    Empty items are preserved. For example, the default converter turns
    `"a,, b,"` into `["a", "", "b", ""]`.

    Args:
        env: Explicit environment variable name.
        default: Default list value.
        factory: Callable that produces a fresh default list.
        converter: Optional converter overriding the built-in splitter.
        delimiter: Delimiter used by the default converter.

    Returns:
        A [`Field`][liblaf.conf.Field] whose converter returns `list[str]`.
    """
    if converter is None:

        def converter(value: str) -> list[str]:
            return [item.strip() for item in value.split(delimiter)]

    return Field(env=env, default=default, factory=factory, converter=converter)

field_path

field_path(
    env: str | None = None,
    default: StrPath | MissingType = MISSING,
    factory: Factory[StrPath] | None = None,
    converter: Converter[Path] | None = None,
) -> Field[Path]

Create a field that normalizes values to Path.

Parameters:

  • env (str | None, default: None ) –

    Explicit environment-variable name.

  • default (StrPath | MissingType, default: MISSING ) –

    Default filesystem path. When provided, it is converted to Path immediately.

  • factory (Factory[StrPath] | None, default: None ) –

    Zero-argument callable used when default is omitted. Its result is wrapped in Path.

  • converter (Converter[Path] | None, default: None ) –

    Optional custom converter. When omitted, Path is used.

Returns:

Source code in src/liblaf/conf/_field_specifiers.py
def field_path(
    env: str | None = None,
    default: StrPath | MissingType = MISSING,
    factory: Factory[StrPath] | None = None,
    converter: Converter[Path] | None = None,
) -> Field[Path]:
    """Create a field that normalizes values to [`Path`][pathlib.Path].

    Args:
        env: Explicit environment-variable name.
        default: Default filesystem path. When provided, it is converted to
            [`Path`][pathlib.Path] immediately.
        factory: Zero-argument callable used when `default` is omitted. Its
            result is wrapped in [`Path`][pathlib.Path].
        converter: Optional custom converter. When omitted,
            [`Path`][pathlib.Path] is used.

    Returns:
        A [`Field`][liblaf.conf.Field] whose converter returns path objects.
    """
    if converter is None:
        converter: Converter[Path] = Path
    if default is not MISSING:
        default = Path(default)
    if factory is not None:
        wrapped: Factory[StrPath] = factory

        def factory() -> Path:
            return Path(wrapped())

    return Field(env=env, default=default, factory=factory, converter=converter)

field_str

field_str(
    env: str | None = None,
    default: str | MissingType = MISSING,
    factory: Factory[str] | None = None,
    converter: Converter[str] | None = None,
) -> Field[str]

Create a field that keeps string values unchanged.

Parameters:

  • env (str | None, default: None ) –

    Explicit environment-variable name.

  • default (str | MissingType, default: MISSING ) –

    Default string value.

  • factory (Factory[str] | None, default: None ) –

    Zero-argument callable used when default is omitted.

  • converter (Converter[str] | None, default: None ) –

    Optional custom converter. When omitted, identity is used.

Returns:

Source code in src/liblaf/conf/_field_specifiers.py
def field_str(
    env: str | None = None,
    default: str | MissingType = MISSING,
    factory: Factory[str] | None = None,
    converter: Converter[str] | None = None,
) -> Field[str]:
    """Create a field that keeps string values unchanged.

    Args:
        env: Explicit environment-variable name.
        default: Default string value.
        factory: Zero-argument callable used when `default` is omitted.
        converter: Optional custom converter. When omitted,
            [`identity`][liblaf.conf.converters.identity] is used.

    Returns:
        A [`Field`][liblaf.conf.Field] whose converter returns `str` values.
    """
    if converter is None:
        converter: Converter[str] = converters.identity
    return Field(env=env, default=default, factory=factory, converter=converter)

field_time

field_time(
    env: str | None = None,
    default: time | MissingType = MISSING,
    factory: Factory[time] | None = None,
    converter: Converter[time] | None = None,
) -> Field[time]

Create a field that parses times from strings.

Parameters:

  • env (str | None, default: None ) –

    Explicit environment-variable name.

  • default (time | MissingType, default: MISSING ) –

    Default time value.

  • factory (Factory[time] | None, default: None ) –

    Zero-argument callable used when default is omitted.

  • converter (Converter[time] | None, default: None ) –

    Optional custom converter. When omitted, Pydantic's pendulum Time adapter is used.

Returns:

Source code in src/liblaf/conf/_field_specifiers.py
def field_time(
    env: str | None = None,
    default: datetime.time | MissingType = MISSING,
    factory: Factory[datetime.time] | None = None,
    converter: Converter[datetime.time] | None = None,
) -> Field[datetime.time]:
    """Create a field that parses times from strings.

    Args:
        env: Explicit environment-variable name.
        default: Default time value.
        factory: Zero-argument callable used when `default` is omitted.
        converter: Optional custom converter. When omitted, Pydantic's
            pendulum `Time` adapter is used.

    Returns:
        A [`Field`][liblaf.conf.Field] whose converter returns
        [`datetime.time`][] values.
    """
    if converter is None:
        converter: Converter[datetime.time] = (
            converters.pydantic_type_adapter_validate_strings(Time)
        )
    return Field(env=env, default=default, factory=factory, converter=converter)

field_timedelta

field_timedelta(
    env: str | None = None,
    default: timedelta | MissingType = MISSING,
    factory: Factory[timedelta] | None = None,
    converter: Converter[timedelta] | None = None,
) -> Field[timedelta]

Create a field that parses duration strings to timedeltas.

Parameters:

  • env (str | None, default: None ) –

    Explicit environment-variable name.

  • default (timedelta | MissingType, default: MISSING ) –

    Default duration value.

  • factory (Factory[timedelta] | None, default: None ) –

    Zero-argument callable used when default is omitted.

  • converter (Converter[timedelta] | None, default: None ) –

    Optional custom converter. When omitted, Pydantic's pendulum Duration adapter is used.

Returns:

Source code in src/liblaf/conf/_field_specifiers.py
def field_timedelta(
    env: str | None = None,
    default: datetime.timedelta | MissingType = MISSING,
    factory: Factory[datetime.timedelta] | None = None,
    converter: Converter[datetime.timedelta] | None = None,
) -> Field[datetime.timedelta]:
    """Create a field that parses duration strings to timedeltas.

    Args:
        env: Explicit environment-variable name.
        default: Default duration value.
        factory: Zero-argument callable used when `default` is omitted.
        converter: Optional custom converter. When omitted, Pydantic's
            pendulum `Duration` adapter is used.

    Returns:
        A [`Field`][liblaf.conf.Field] whose converter returns
        [`datetime.timedelta`][] values.
    """
    if converter is None:
        converter: Converter[datetime.timedelta] = (
            converters.pydantic_type_adapter_validate_strings(Duration)
        )
    return Field(env=env, default=default, factory=factory, converter=converter)

group

group[T](factory: type[T]) -> Group[T]
group[T](factory: Callable[[], T]) -> Group[T]

Create a Group descriptor.

Parameters:

  • factory (Callable[[], T]) –

    A config class or zero-argument callable that creates the nested object.

Returns:

  • Group[T]

    A group descriptor that caches one factory result per owning instance.

Source code in src/liblaf/conf/_group.py
def group[T](factory: Callable[[], T]) -> Group[T]:
    """Create a [`Group`][liblaf.conf.Group] descriptor.

    Args:
        factory: A config class or zero-argument callable that creates the
            nested object.

    Returns:
        A group descriptor that caches one factory result per owning instance.
    """
    return Group(factory)