cfx

cfx - lightweight self-documenting configuration classes.

Declare typed, validated, and documented configuration fields directly on the class that uses them, using annotations and Field():

from cfx import Config, Field
from typing import Literal

class SearchConfig(Config):
    """Configuration for the main search algorithm."""
    confid = "search"

    n_sigma: float = Field(5.0, "Detection threshold", minval=0.0)
    method: Literal["DBSCAN", "RANSAC"] = Field("DBSCAN", "Algorithm")
    debug: bool = Field(False, "Enable verbose debug output")

cfg = SearchConfig()
cfg.n_sigma = 3.0        # validated immediately
cfg["method"] = "RANSAC" # dict-style access also works
print(cfg)               # tabulated Key / Value / Description table
d = cfg.to_dict()
cfg2 = SearchConfig.from_dict(d)

For custom field types with advanced validation, import explicit types:

from cfx.types import Float, Options, ConfigField

Submodules

Exceptions

FrozenConfigError

Raised when attempting to set a field on a frozen Config instance.

Classes

Config

Base class for all user-defined configuration classes.

ComponentRef

Descriptor installed on a Config class for each component slot.

FieldRef

A reference to a field on a Config class.

ConfigField

Base descriptor for a single configuration field.

FieldSpec

Placeholder returned by Field(); resolved at class-definition time.

Any

A field that accepts any value without validation.

String

A field that validates string values.

Int

A field that validates integer values.

Float

A field that validates floating-point values.

Scalar

A field that validates numeric (int or float) values.

Bool

A field that validates boolean values.

Options

A field whose value must be one of a fixed set of choices.

MultiOptions

A field whose value must be a subset of a fixed set of choices.

Path

A field that coerces and validates filesystem paths.

Seed

A field for random-number-generator seeds.

Range

A field for a linear (min, max) numeric range.

List

A field that validates list values.

Dict

A field that validates dict values.

Date

A field that validates datetime.date values.

Time

A field that validates datetime.time values.

DateTime

A field that validates datetime.datetime values.

Alias

A view field that delegates reads and writes to a dotpath on the

Mirror

A config field that keeps multiple dotpaths in sync.

AliasedView

A self-contained view that owns its component instances.

ConfigView

Base class for curated projections over a Config instance.

FlatView

An AliasedView with no component prefix.

Functions

Field(default[, doc])

Declare an annotation-native config field.

resolve_field_spec(name, spec, annotation)

Instantiate the right ConfigField subclass for an annotation.

Package Contents

class cfx.Config(**kwargs)[source]

Base class for all user-defined configuration classes.

Subclass Config and declare ConfigField instances as class attributes to define a configuration schema. Fields are validated on assignment, self-documenting via __str__, and composable via inheritance or the components= keyword.

Parameters:
**kwargsobject

Initial field values passed as keyword arguments. Each keyword must match a declared field name and is validated on assignment.

Attributes:
confidstr

Identifier for this config class. Used as the dict key in nested serialization and as the attribute name under which this config is accessible on a parent config in nested composition mode. Defaults to the lowercased class name when not explicitly set, so class SearchConfig(Config) gets confid = "searchconfig" automatically.

Examples

>>> from cfx import Config, Field
>>> class BaseConfig(Config):
...     confid = "base"
...     n: int = Field(5, "An integer field", minval=0)
...     label: str = Field("default", "A label")
>>> cfg = BaseConfig()
>>> cfg.n
5
>>> cfg.n = 3
>>> cfg["label"] = "custom"
>>> print(cfg)
BaseConfig:
Key   | Value  | Description
------+--------+----------------
n     | 3      | An integer field
label | custom | A label
confid: str = 'config'

Name of this config class when it’s used as a component config. Automatically set as the lowercase version of the class name.

classmethod __init_subclass__(components=None, **kwargs)[source]
validate()[source]

Validate cross-field constraints.

The base implementation is a no-op. Override in subclasses to add validation logic that involves more than one field. Called automatically after deserialization via from_dict, from_yaml, and from_toml.

Raises:
ValueError

If any cross-field constraint is violated.

Examples

>>> from cfx import Config, Field
>>> class BandConfig(Config):
...     low: float = Field(1.0, "Lower bound", minval=0.0)
...     high: float = Field(2.0, "Upper bound", minval=0.0)
...
...     def validate(self):
...         if self.high <= self.low:
...             raise ValueError("high must be greater than low")
__str__()[source]
__repr__()[source]
__setattr__(name, value)[source]
__getitem__(key)[source]
__setitem__(key, value)[source]
__iter__()[source]
__contains__(key)[source]
__eq__(other)[source]
keys()[source]

Return a set-like object providing a view on the dict’s keys.

values()[source]

Return the current values of all declared fields.

Returns:
valueslist

Current field values in declaration order.

items()[source]

Return (name, value) pairs for all declared fields.

Returns:
pairslist[tuple]

(field_name, current_value) pairs in declaration order.

update(mapping)[source]

Set multiple field values from a mapping.

Each key-value pair is set via setattr, routing through the descriptor’s validate method. Nested sub-configs can be updated by passing the confid as the key with a dict value (which is applied recursively) or a Config instance (which replaces the sub-config entirely).

Parameters:
mappingdict

Field names and their new values. Nested confids are accepted with a dict or Config value.

Raises:
KeyError

If any key in mapping is not a declared field or nested confid.

TypeError

If a nested confid key is given a value that is neither a dict nor a Config instance.

freeze()[source]

Make this config instance read-only.

After calling freeze, any attempt to set a field or replace a nested sub-config raises FrozenConfigError. The freeze propagates recursively to all nested sub-configs.

diff(other)[source]

Return fields that differ between this config and another.

Recurses into nested sub-configs. Keys for nested differences use dot notation: "search.n_sigma".

Parameters:
otherConfig

Another config instance of the same class to compare against.

Returns:
diffsdict

Mapping of field name (or "confid.field") to (self_value, other_value) for every field whose value differs.

Raises:
TypeError

If other is not the same type as this config.

copy(**overrides)[source]

Return a new instance with optionally overridden field values.

Parameters:
**overridesobject

Field names and replacement values applied after copying all current field values.

Returns:
cfgConfig

A new instance of the same class with the same field values, except where overridden.

Examples

>>> from cfx import Config, Field
>>> class C(Config):
...     x: int = Field(1, "x")
...     y: str = Field("hello", "y")
>>> base = C()
>>> modified = base.copy(x=42, y="world")
>>> modified.x, modified.y
(42, 'world')
classmethod from_dict(mapping, strict=True)[source]

Create an instance from a plain dict.

Parameters:
mappingdict

Field names and values.

strictbool, optional

If True (default), raises KeyError for any key in mapping that is not a declared field. If False, unknown keys are silently ignored, which is useful when loading configs saved by an older version of the class.

Returns:
cfgConfig

A new instance with values from mapping.

Raises:
KeyError

If strict is True and mapping contains an undeclared field name.

to_dict()[source]

Serialize this config to a plain dict.

Returns:
ddict

Mapping of field names to their current values. Nested Config sub-objects are serialized recursively. pathlib.Path values are serialized as strings so the result is always JSON/YAML/TOML-safe.

classmethod from_yaml(text, strict=True)[source]

Create an instance from a YAML string.

Parameters:
textstr

YAML-encoded config.

strictbool, optional

Passed to from_dict. Default is True.

Returns:
cfgConfig

A new instance with values from the YAML.

Raises:
ImportError

If pyyaml is not installed.

to_yaml()[source]

Serialize this config to a YAML string.

Returns:
yaml_strstr

YAML representation of the config.

Raises:
ImportError

If pyyaml is not installed.

classmethod add_arguments(parser, prefix='')[source]

Register all non-static fields as arguments on parser.

For nested configs the component’s confid is used as the dot-notation prefix: field n_sigma in a sub-config with confid = "search" becomes --search.n-sigma. An explicit prefix overrides the automatic one, which is useful when composing multiple configs into a shared parser manually.

Parameters:
parserargparse.ArgumentParser

The parser to register arguments on.

prefixstr, optional

Dot-separated prefix prepended to every flag name. Default "".

classmethod from_argparse(namespace)[source]

Build a Config instance from a parsed argparse namespace.

If the namespace contains a config_file value (registered by add_arguments), that file is loaded first and CLI flags are applied on top. Without a config file, class-level defaults are used as the base.

Parameters:
namespaceargparse.Namespace

Result of parser.parse_args().

Returns:
cfgConfig

A new instance with values taken from the namespace. Fields absent from the namespace (value None) keep their base defaults.

classmethod click_options()[source]

Return a decorator that registers all fields as click options.

Stack on a @click.command() function:

@click.command()
@RunConfig.click_options()
def run(**kwargs):
    cfg = RunConfig.from_click(kwargs)
Returns:
decoratorcallable

A decorator that applies all click.option decorators for this config’s fields to the target function.

Raises:
ImportError

If click is not installed.

classmethod from_click(params)[source]

Build a Config instance from click’s **kwargs dict.

Pass the kwargs dict received by the decorated command function:

@click.command()
@RunConfig.click_options()
def run(**kwargs):
    cfg = RunConfig.from_click(kwargs)
Parameters:
paramsdict

The **kwargs received by the click-decorated function. Keys use double underscores as separators (e.g. search__n_sigma).

Returns:
cfgConfig

A new instance with all non-None param values applied.

exception cfx.FrozenConfigError[source]

Bases: AttributeError

Raised when attempting to set a field on a frozen Config instance.

Inherits from AttributeError so that standard attribute-protection machinery recognises it correctly.

class cfx.ComponentRef(confid, cls)[source]

Descriptor installed on a Config class for each component slot.

Installed automatically by _ConfigType after _nested_classes is built. Returns a FieldRef on class-level access so component paths can be used in Alias and Mirror declarations. On instance access returns the stored sub-config instance as normal.

confid
cls
__set_name__(owner, name)[source]
__get__(obj, objtype=None)[source]
class cfx.FieldRef(path, resolved_cls)[source]

A reference to a field on a Config class.

Obtained by accessing a field or component as a class attribute rather than on an instance. Attribute chains are validated against the schema at definition time — a typo in the path raises AttributeError immediately, not at the first runtime access.

Pass a FieldRef to Alias or Mirror instead of a plain string to keep paths refactorable via normal IDE rename and go-to-definition tools.

Examples

>>> from cfx import Config, Field, Alias
>>> class Inner(Config):
...     x: float = Field(1.0, "x value")
>>> class Outer(Config, components=[Inner]):
...     pass
>>> Outer.inner.x
FieldRef(...)
>>> Alias(Outer.inner.x)
<...Alias object at ...>
__getattr__(name)[source]
__repr__()[source]
class cfx.ConfigField(default_value, doc, static=False, env=None, transient=None)[source]

Bases: Generic[T]

Base descriptor for a single configuration field.

Implements __get__, __set__, and __set_name__ so that instances assigned as class attributes behave as managed, validated attributes on Config subclasses.

The default value may be a plain object or a callable that accepts the owning instance as its sole argument (a lazy factory). When a lazy factory is provided, the computed value is returned on every access until the user explicitly sets the attribute, after which the stored value is used instead.

Parameters:
default_valueobject or callable

Default value for the field. If callable, it is treated as a lazy factory: default_value(instance) is called on each __get__ invocation until an explicit value is stored on the instance.

docstr

Human-readable description shown in __str__ tables and Jupyter _repr_html_ output.

staticbool, optional

If True the value is frozen to default_value at class-definition time and cannot be changed on instances. Any attempted __set__ raises AttributeError. Default is False.

envstr or None, optional

Name of an environment variable to consult when no explicit value has been stored on the instance. When set, the priority chain is: explicit assignment > environment variable > default. The raw string from os.environ is coerced by _from_env_str and then validated. The env value is not stored on the instance - it is re-read on every access, matching the behaviour of callable defaults. None means no environment variable is consulted. Default is None.

Raises:
TypeError

If default_value (when not callable) fails validate.

ValueError

If default_value (when not callable) fails validate.

Examples

>>> from cfx import Config
>>> from cfx.types import ConfigField
>>> class MyConfig(Config):
...     name = ConfigField("default", "A simple untyped field")
>>> cfg = MyConfig()
>>> cfg.name
'default'
>>> cfg.name = "something else"
>>> cfg.name
'something else'
doc
static = False
env = None
property transient

True when the field is skipped on serialization if no value stored.

normalize(value)[source]

Transform value to canonical form before validation and storage.

Called before validate in both __init__ (for non-callable defaults) and __set__. Must be idempotent: applying normalize twice yields the same result as applying it once.

Override in subclasses to coerce common input types to the field’s canonical type. Examples: str -> pathlib.Path, list -> tuple, angular wrap-around to [0, 360).

The default implementation returns the value unchanged.

Parameters:
valueobject

The raw value to normalize.

Returns:
object

The normalized value, ready to pass to validate.

validate(value)[source]

Validate a value against this field’s constraints.

Called after normalize. Override in subclasses to enforce correct type or range of values. Raise TypeError for wrong type, and ValueError for out-of-range error. The base implementation accepts any value.

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

from_string(s)[source]

Parse a raw string into this field’s type.

Override in subclasses to coerce the raw string to the appropriate type for a particular ConfigField. The default implementation returns the unchanged string.

Called by __get__ when env is set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparse type= callable. The result is then passed to validate.

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

to_string(value)[source]

Format a field value as a human-readable string for display.

Called by the display layer when rendering the config table. Override in subclasses to produce cleaner output than Python’s default str(). The default implementation returns str(value).

Parameters:
valueobject

The current field value.

Returns:
sstr

Display string for the value.

serialize(value)[source]

Serialize value to a JSON/YAML-safe form for to_dict().

Override in subclasses for types that need a different on-disk representation (e.g. pathlib.Path -> str, set -> sorted list, datetime.time -> ISO string). The default returns the value unchanged.

Parameters:
valueobject

The current field value (already normalized/canonical).

Returns:
object

A JSON/YAML-safe value.

deserialize(value)[source]

Deserialize a value from dict form back to the field’s type.

Logical inverse of serialize. Called by from_dict() before setattr; the result is then passed through normalize and validate via __set__. The default returns the value unchanged.

Parameters:
valueobject

The value from the dict.

Returns:
object

The deserialized value, ready to be set on the instance.

is_set(obj)[source]

Return True if an explicit value is stored on obj.

Returns False when the field is still using its default, env var, or callable factory.

Parameters:
objConfig

Instance to check.

unset(obj)[source]

Remove the stored value, reverting to default/env/callable.

After calling this, __get__ will re-evaluate the default, environment variable, or callable factory on the next access.

Parameters:
objConfig

Instance to modify.

reset(obj, value=None)[source]

Reset to default or set a new value with full normalize/validate.

If value is None, equivalent to unset. Otherwise, sets a new value going through the full normalize -> validate pipeline.

Parameters:
objConfig

Instance to modify.

valueobject, optional

New value. If None, reverts to default.

to_argparse_kwargs(name, prefix='')[source]

Return kwargs dict for parser.add_argument().

The returned dict always contains a "flag" key with the full option string (e.g. "--search.n-sigma"). Pull it out before calling argparse:

kwargs = descriptor.to_argparse_kwargs(name, prefix)
flag = kwargs.pop("flag")
parser.add_argument(flag, **kwargs)

Override in subclasses to customize the argparse representation (add "choices", "nargs", "action", "metavar").

Parameters:
namestr

Field attribute name.

prefixstr, optional

Dot-separated prefix for nested configs (e.g. "search").

Returns:
dict
to_click_option(name, prefix='')[source]

Return a click.option() decorator for this field.

Override in subclasses to customize the click representation.

Parameters:
namestr

Field attribute name.

prefixstr, optional

Dot-separated prefix for nested configs.

Returns:
decorator

A click.option(...) decorator ready to stack on a command.

Raises:
ImportError

If click is not installed.

__repr__()[source]
__str__()[source]
__set_name__(owner, name)[source]

Record the attribute name assigned by the owning class.

Called automatically by the metaclass machinery when the descriptor is assigned as a class attribute. Sets public_name (the name as written in the class body) and private_name (the name used to store the per-instance value in instance.__dict__).

Parameters:
ownertype

The class that owns this descriptor.

namestr

The attribute name under which this descriptor was assigned.

__get__(obj, objtype)[source]
__get__(obj: object, objtype: type) T

Return the field value for the owning instance.

If accessed on the class (obj is None) returns a FieldRef path proxy, enabling IDE-refactorable paths for use in Alias and Mirror declarations.

For static fields, always returns defaultval.

For non-static fields with no explicitly stored value, the lookup order is:

  • explicit assignment (stored on the instance)

  • environment variable, when env is set and the variable is present in os.environ

  • defaultval, called if callable, returned directly otherwise

Parameters:
objConfig or None

The owning instance, or None when accessed on the class.

objtypetype, optional

The owning class.

Returns:
valueobject

The field value, or a FieldRef path proxy when obj is None.

__set__(obj, value)[source]

Set the field value on the owning instance.

Full pipeline: normalize -> validate -> store.

Parameters:
objConfig

The owning instance.

valueobject

The new value. Passed through normalize then validate before being stored.

Raises:
AttributeError

If the field is declared static=True.

TypeError

If the value fails validate.

ValueError

If the value fails validate.

cfx.Field(default, doc='', **kwargs)[source]

Declare an annotation-native config field.

Use as the right-hand side of a type-annotated class attribute on a Config subclass. The concrete ConfigField subclass is inferred from the annotation at class-definition time:

from typing import Literal
from cfx import Config, Field

class SearchConfig(Config):
    n_sigma: float = Field(5.0, "Detection threshold", minval=0.0)
    method: Literal["DBSCAN", "RANSAC"] = Field("DBSCAN", "Algorithm")
    verbose: bool = Field(False, "Enable verbose output")

Callable defaults are supported for computed fields:

class DerivedConfig(Config):
    base: float = Field(1.0, "Base value")
    derived: float = Field(lambda self: self.base * 2, "Derived value")
Parameters:
defaultobject or callable

Default value or lazy factory accepting the owning instance.

docstr, optional

Human-readable description shown in display tables.

**kwargs

Any keyword argument accepted by the resolved field type (e.g. minval=, maxval=, env=, static=, transient=).

Returns:
specFieldSpec

Placeholder resolved to a ConfigField at class-definition time.

class cfx.FieldSpec(default, doc, **kwargs)[source]

Placeholder returned by Field(); resolved at class-definition time.

Users should not instantiate this directly — use Field() instead. Config.__init_subclass__ replaces every FieldSpec with the appropriate ConfigField subclass before any instance is created.

default
doc
kwargs
cfx.resolve_field_spec(name, spec, annotation)[source]

Instantiate the right ConfigField subclass for an annotation.

Called by Config.__init_subclass__ for every FieldSpec in the class body. Not part of the end-user API but importable for advanced use.

Parameters:
namestr

The attribute name (used in error messages).

specFieldSpec

The placeholder carrying default, doc, and extra kwargs.

annotationtype

The resolved type annotation for this attribute.

Returns:
fieldConfigField

A fully constructed field descriptor.

Raises:
TypeError

If the annotation cannot be mapped to a known ConfigField type.

class cfx.Any(default_value, doc, static=False, env=None, transient=None)[source]

Bases: cfx.types.config_field.ConfigField

A field that accepts any value without validation.

Use this as an explicit escape hatch when validation is intentionally deferred to Config.validate or handled externally. The Any name signals intent: the author has consciously opted out of field-level constraints.

Parameters:
default_valueobject or callable

Default value or lazy factory.

docstr

Documentation.

staticbool, optional

If True, the value is frozen at class-definition time. Default is False.

class cfx.String(default_value, doc, minsize=0, maxsize=None, predicate=None, static=False, env=None, transient=None)[source]

Bases: cfx.types.config_field.ConfigField

A field that validates string values.

Parameters:
default_valuestr or callable

Default string value or lazy factory returning a str.

docstr

Documentation.

minsizeint, optional

Minimum allowed string length. Default is 0.

maxsizeint or None, optional

Maximum allowed string length. None means no upper limit. Default is None.

predicatecallable or None, optional

Additional validation callable that accepts a str and returns True if the value is valid. Default is None.

staticbool, optional

If True, the value is frozen at class-definition time. Default is False.

Raises:
TypeError

If the value is not a str.

ValueError

If the value does not satisfy the length or predicate constraints.

minsize = 0
maxsize = None
predicate = None
validate(value)[source]

Validate a value against this field’s constraints.

Called after normalize. Override in subclasses to enforce correct type or range of values. Raise TypeError for wrong type, and ValueError for out-of-range error. The base implementation accepts any value.

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

class cfx.Int(default_value, doc, minval=None, maxval=None, static=False, env=None, transient=None)[source]

Bases: cfx.types.config_field.ConfigField

A field that validates integer values.

Parameters:
default_valueint or callable

Default integer value or lazy factory returning an int.

docstr

Documentation.

minvalint or None, optional

Minimum allowed value (inclusive). Default is None.

maxvalint or None, optional

Maximum allowed value (inclusive). Default is None.

staticbool, optional

If True, the value is frozen at class-definition time. Default is False.

envstr or None, optional

Environment variable name. See ConfigField.

Raises:
TypeError

If the value is not an int.

ValueError

If the value is outside [minval, maxval].

minval = None
maxval = None
from_string(s)[source]

Parse a raw string into this field’s type.

Override in subclasses to coerce the raw string to the appropriate type for a particular ConfigField. The default implementation returns the unchanged string.

Called by __get__ when env is set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparse type= callable. The result is then passed to validate.

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

validate(value)[source]

Validate a value against this field’s constraints.

Called after normalize. Override in subclasses to enforce correct type or range of values. Raise TypeError for wrong type, and ValueError for out-of-range error. The base implementation accepts any value.

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

class cfx.Float(default_value, doc, minval=None, maxval=None, static=False, env=None, transient=None)[source]

Bases: cfx.types.config_field.ConfigField

A field that validates floating-point values.

Parameters:
default_valuefloat or callable

Default float value or lazy factory returning a float.

docstr

Documentation.

minvalfloat or None, optional

Minimum allowed value (inclusive). Default is None.

maxvalfloat or None, optional

Maximum allowed value (inclusive). Default is None.

staticbool, optional

If True, the value is frozen at class-definition time. Default is False.

envstr or None, optional

Environment variable name. See ConfigField.

Raises:
TypeError

If the value is not a float or int (ints are coerced).

ValueError

If the value is outside [minval, maxval].

minval = None
maxval = None
from_string(s)[source]

Parse a raw string into this field’s type.

Override in subclasses to coerce the raw string to the appropriate type for a particular ConfigField. The default implementation returns the unchanged string.

Called by __get__ when env is set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparse type= callable. The result is then passed to validate.

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

validate(value)[source]

Validate a value against this field’s constraints.

Called after normalize. Override in subclasses to enforce correct type or range of values. Raise TypeError for wrong type, and ValueError for out-of-range error. The base implementation accepts any value.

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

class cfx.Scalar(default_value, doc, minval=None, maxval=None, static=False, env=None, transient=None)[source]

Bases: cfx.types.config_field.ConfigField

A field that validates numeric (int or float) values.

Use this when both integers and floats are acceptable. For fields that must be strictly one numeric type, prefer Int or Float.

Parameters:
default_valuenumbers.Number or callable

Default numeric value or lazy factory returning a number.

docstr

Documentation.

minvalnumbers.Number or None, optional

Minimum allowed value (inclusive). Default is None.

maxvalnumbers.Number or None, optional

Maximum allowed value (inclusive). Default is None.

staticbool, optional

If True, the value is frozen at class-definition time. Default is False.

Raises:
TypeError

If the value is not a numbers.Number.

ValueError

If the value is outside [minval, maxval].

minval = None
maxval = None
from_string(s)[source]

Parse a raw string into this field’s type.

Override in subclasses to coerce the raw string to the appropriate type for a particular ConfigField. The default implementation returns the unchanged string.

Called by __get__ when env is set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparse type= callable. The result is then passed to validate.

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

validate(value)[source]

Validate a value against this field’s constraints.

Called after normalize. Override in subclasses to enforce correct type or range of values. Raise TypeError for wrong type, and ValueError for out-of-range error. The base implementation accepts any value.

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

class cfx.Bool(default_value, doc, static=False, env=None, transient=None)[source]

Bases: cfx.types.config_field.ConfigField

A field that validates boolean values.

Parameters:
default_valuebool or callable

Default boolean value or lazy factory returning a bool.

docstr

Documentation.

staticbool, optional

If True, the value is frozen at class-definition time. Default is False.

Raises:
TypeError

If the value is not a bool.

from_string(s)[source]

Parse a raw string into this field’s type.

Override in subclasses to coerce the raw string to the appropriate type for a particular ConfigField. The default implementation returns the unchanged string.

Called by __get__ when env is set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparse type= callable. The result is then passed to validate.

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

validate(value)[source]

Validate a value against this field’s constraints.

Called after normalize. Override in subclasses to enforce correct type or range of values. Raise TypeError for wrong type, and ValueError for out-of-range error. The base implementation accepts any value.

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

to_argparse_kwargs(name, prefix='')[source]

Return kwargs dict for parser.add_argument().

The returned dict always contains a "flag" key with the full option string (e.g. "--search.n-sigma"). Pull it out before calling argparse:

kwargs = descriptor.to_argparse_kwargs(name, prefix)
flag = kwargs.pop("flag")
parser.add_argument(flag, **kwargs)

Override in subclasses to customize the argparse representation (add "choices", "nargs", "action", "metavar").

Parameters:
namestr

Field attribute name.

prefixstr, optional

Dot-separated prefix for nested configs (e.g. "search").

Returns:
dict
to_click_option(name, prefix='')[source]

Return a click.option() decorator for this field.

Override in subclasses to customize the click representation.

Parameters:
namestr

Field attribute name.

prefixstr, optional

Dot-separated prefix for nested configs.

Returns:
decorator

A click.option(...) decorator ready to stack on a command.

Raises:
ImportError

If click is not installed.

class cfx.Options(options, doc, default_value=None, static=False, env=None, transient=None)[source]

Bases: cfx.types.config_field.ConfigField

A field whose value must be one of a fixed set of choices.

Parameters:
optionstuple or list

Allowed values. The first element is used as the default unless default_value is provided.

docstr

Documentation.

default_valueobject, optional

Default value. Must be a member of options. Defaults to options[0].

staticbool, optional

If True, the value is frozen at class-definition time. Default is False.

Raises:
ValueError

If the value being set is not in options.

Examples

>>> from cfx import Config
>>> from cfx.types import Options
>>> class BaseConfig(Config):
...     mode = Options(("fast", "balanced", "thorough"), "Processing mode")
>>> cfg = BaseConfig()
>>> cfg.mode
'fast'
>>> cfg.mode = "thorough"
>>> cfg.mode = "turbo"
Traceback (most recent call last):
    ...
ValueError: Expected 'turbo' to be one of ('fast', 'balanced', 'thorough')
options
validate(value)[source]

Validate a value against this field’s constraints.

Called after normalize. Override in subclasses to enforce correct type or range of values. Raise TypeError for wrong type, and ValueError for out-of-range error. The base implementation accepts any value.

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

to_argparse_kwargs(name, prefix='')[source]

Return kwargs dict for parser.add_argument().

The returned dict always contains a "flag" key with the full option string (e.g. "--search.n-sigma"). Pull it out before calling argparse:

kwargs = descriptor.to_argparse_kwargs(name, prefix)
flag = kwargs.pop("flag")
parser.add_argument(flag, **kwargs)

Override in subclasses to customize the argparse representation (add "choices", "nargs", "action", "metavar").

Parameters:
namestr

Field attribute name.

prefixstr, optional

Dot-separated prefix for nested configs (e.g. "search").

Returns:
dict
to_click_option(name, prefix='')[source]

Return a click.option() decorator for this field.

Override in subclasses to customize the click representation.

Parameters:
namestr

Field attribute name.

prefixstr, optional

Dot-separated prefix for nested configs.

Returns:
decorator

A click.option(...) decorator ready to stack on a command.

Raises:
ImportError

If click is not installed.

class cfx.MultiOptions(options, doc, default_value=None, static=False, env=None, transient=None)[source]

Bases: cfx.types.config_field.ConfigField

A field whose value must be a subset of a fixed set of choices.

Parameters:
optionstuple or list

Full set of allowed values.

docstr

Documentation.

default_valueset or frozenset, optional

Default selection. Defaults to an empty set.

staticbool, optional

If True, the value is frozen at class-definition time. Default is False.

Raises:
TypeError

If the value is not a set or frozenset.

ValueError

If the value contains elements not in options.

Examples

>>> from cfx import Config
>>> from cfx.types import MultiOptions
>>> class PipelineConfig(Config):
...     steps = MultiOptions(
...         ("preprocess", "detect", "cluster", "output"),
...         "Pipeline steps to run",
...         default_value={"preprocess", "detect"},
...     )
options
normalize(value)[source]

Transform value to canonical form before validation and storage.

Called before validate in both __init__ (for non-callable defaults) and __set__. Must be idempotent: applying normalize twice yields the same result as applying it once.

Override in subclasses to coerce common input types to the field’s canonical type. Examples: str -> pathlib.Path, list -> tuple, angular wrap-around to [0, 360).

The default implementation returns the value unchanged.

Parameters:
valueobject

The raw value to normalize.

Returns:
object

The normalized value, ready to pass to validate.

validate(value)[source]

Validate a value against this field’s constraints.

Called after normalize. Override in subclasses to enforce correct type or range of values. Raise TypeError for wrong type, and ValueError for out-of-range error. The base implementation accepts any value.

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

serialize(value)[source]

Serialize value to a JSON/YAML-safe form for to_dict().

Override in subclasses for types that need a different on-disk representation (e.g. pathlib.Path -> str, set -> sorted list, datetime.time -> ISO string). The default returns the value unchanged.

Parameters:
valueobject

The current field value (already normalized/canonical).

Returns:
object

A JSON/YAML-safe value.

deserialize(value)[source]

Deserialize a value from dict form back to the field’s type.

Logical inverse of serialize. Called by from_dict() before setattr; the result is then passed through normalize and validate via __set__. The default returns the value unchanged.

Parameters:
valueobject

The value from the dict.

Returns:
object

The deserialized value, ready to be set on the instance.

from_string(s)[source]

Parse a raw string into this field’s type.

Override in subclasses to coerce the raw string to the appropriate type for a particular ConfigField. The default implementation returns the unchanged string.

Called by __get__ when env is set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparse type= callable. The result is then passed to validate.

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

to_string(value)[source]

Format a field value as a human-readable string for display.

Called by the display layer when rendering the config table. Override in subclasses to produce cleaner output than Python’s default str(). The default implementation returns str(value).

Parameters:
valueobject

The current field value.

Returns:
sstr

Display string for the value.

to_argparse_kwargs(name, prefix='')[source]

Return kwargs dict for parser.add_argument().

The returned dict always contains a "flag" key with the full option string (e.g. "--search.n-sigma"). Pull it out before calling argparse:

kwargs = descriptor.to_argparse_kwargs(name, prefix)
flag = kwargs.pop("flag")
parser.add_argument(flag, **kwargs)

Override in subclasses to customize the argparse representation (add "choices", "nargs", "action", "metavar").

Parameters:
namestr

Field attribute name.

prefixstr, optional

Dot-separated prefix for nested configs (e.g. "search").

Returns:
dict
to_click_option(name, prefix='')[source]

Return a click.option() decorator for this field.

Override in subclasses to customize the click representation.

Parameters:
namestr

Field attribute name.

prefixstr, optional

Dot-separated prefix for nested configs.

Returns:
decorator

A click.option(...) decorator ready to stack on a command.

Raises:
ImportError

If click is not installed.

class cfx.Path(default_value, doc, must_exist=False, static=False, env=None, transient=None)[source]

Bases: cfx.types.config_field.ConfigField

A field that coerces and validates filesystem paths.

Accepts str or pathlib.Path values and stores them as pathlib.Path objects.

Parameters:
default_valuestr, pathlib.Path, or callable

Default path value or lazy factory. Strings are coerced to pathlib.Path on assignment.

docstr

Documentation.

must_existbool, optional

If True, raises ValueError when the path does not exist on the filesystem at the time of assignment. Default is False.

staticbool, optional

If True, the value is frozen at class-definition time. Default is False.

Raises:
TypeError

If the value cannot be coerced to a pathlib.Path.

ValueError

If must_exist is True and the path does not exist.

must_exist = False
normalize(value)[source]

Transform value to canonical form before validation and storage.

Called before validate in both __init__ (for non-callable defaults) and __set__. Must be idempotent: applying normalize twice yields the same result as applying it once.

Override in subclasses to coerce common input types to the field’s canonical type. Examples: str -> pathlib.Path, list -> tuple, angular wrap-around to [0, 360).

The default implementation returns the value unchanged.

Parameters:
valueobject

The raw value to normalize.

Returns:
object

The normalized value, ready to pass to validate.

validate(value)[source]

Validate a value against this field’s constraints.

Called after normalize. Override in subclasses to enforce correct type or range of values. Raise TypeError for wrong type, and ValueError for out-of-range error. The base implementation accepts any value.

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

serialize(value)[source]

Serialize value to a JSON/YAML-safe form for to_dict().

Override in subclasses for types that need a different on-disk representation (e.g. pathlib.Path -> str, set -> sorted list, datetime.time -> ISO string). The default returns the value unchanged.

Parameters:
valueobject

The current field value (already normalized/canonical).

Returns:
object

A JSON/YAML-safe value.

deserialize(value)[source]

Deserialize a value from dict form back to the field’s type.

Logical inverse of serialize. Called by from_dict() before setattr; the result is then passed through normalize and validate via __set__. The default returns the value unchanged.

Parameters:
valueobject

The value from the dict.

Returns:
object

The deserialized value, ready to be set on the instance.

from_string(s)[source]

Parse a raw string into this field’s type.

Override in subclasses to coerce the raw string to the appropriate type for a particular ConfigField. The default implementation returns the unchanged string.

Called by __get__ when env is set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparse type= callable. The result is then passed to validate.

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

to_string(value)[source]

Format a field value as a human-readable string for display.

Called by the display layer when rendering the config table. Override in subclasses to produce cleaner output than Python’s default str(). The default implementation returns str(value).

Parameters:
valueobject

The current field value.

Returns:
sstr

Display string for the value.

to_argparse_kwargs(name, prefix='')[source]

Return kwargs dict for parser.add_argument().

The returned dict always contains a "flag" key with the full option string (e.g. "--search.n-sigma"). Pull it out before calling argparse:

kwargs = descriptor.to_argparse_kwargs(name, prefix)
flag = kwargs.pop("flag")
parser.add_argument(flag, **kwargs)

Override in subclasses to customize the argparse representation (add "choices", "nargs", "action", "metavar").

Parameters:
namestr

Field attribute name.

prefixstr, optional

Dot-separated prefix for nested configs (e.g. "search").

Returns:
dict
class cfx.Seed(default_value, doc, static=False, env=None, transient=None)[source]

Bases: cfx.types.config_field.ConfigField

A field for random-number-generator seeds.

Accepts an int or None. A value of None signals that the seed should be chosen randomly at runtime, distinct from any specific integer seed including zero.

Parameters:
default_valueint, None, or callable

Default seed value or lazy factory.

docstr

Documentation.

staticbool, optional

If True, the value is frozen at class-definition time. Default is False.

Raises:
TypeError

If the value is not an int or None.

from_string(s)[source]

Parse a raw string into this field’s type.

Override in subclasses to coerce the raw string to the appropriate type for a particular ConfigField. The default implementation returns the unchanged string.

Called by __get__ when env is set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparse type= callable. The result is then passed to validate.

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

validate(value)[source]

Validate a value against this field’s constraints.

Called after normalize. Override in subclasses to enforce correct type or range of values. Raise TypeError for wrong type, and ValueError for out-of-range error. The base implementation accepts any value.

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

to_argparse_kwargs(name, prefix='')[source]

Return kwargs dict for parser.add_argument().

The returned dict always contains a "flag" key with the full option string (e.g. "--search.n-sigma"). Pull it out before calling argparse:

kwargs = descriptor.to_argparse_kwargs(name, prefix)
flag = kwargs.pop("flag")
parser.add_argument(flag, **kwargs)

Override in subclasses to customize the argparse representation (add "choices", "nargs", "action", "metavar").

Parameters:
namestr

Field attribute name.

prefixstr, optional

Dot-separated prefix for nested configs (e.g. "search").

Returns:
dict
class cfx.Range(default_value, doc, static=False, env=None, transient=None)[source]

Bases: cfx.types.config_field.ConfigField

A field for a linear (min, max) numeric range.

Stores a two-element tuple (min, max) and validates that min < max. This field is intentionally limited to linear ranges. Cyclical or angular ranges (e.g. 350 deg to 10 deg crossing zero) are out of scope because their validation depends on domain-specific conventions.

Parameters:
default_valuetuple[numbers.Number, numbers.Number] or callable

Default (min, max) tuple or lazy factory.

docstr

Documentation.

staticbool, optional

If True, the value is frozen at class-definition time. Default is False.

Raises:
TypeError

If the value is not a two-element sequence of numbers.

ValueError

If min >= max.

normalize(value)[source]

Transform value to canonical form before validation and storage.

Called before validate in both __init__ (for non-callable defaults) and __set__. Must be idempotent: applying normalize twice yields the same result as applying it once.

Override in subclasses to coerce common input types to the field’s canonical type. Examples: str -> pathlib.Path, list -> tuple, angular wrap-around to [0, 360).

The default implementation returns the value unchanged.

Parameters:
valueobject

The raw value to normalize.

Returns:
object

The normalized value, ready to pass to validate.

serialize(value)[source]

Serialize value to a JSON/YAML-safe form for to_dict().

Override in subclasses for types that need a different on-disk representation (e.g. pathlib.Path -> str, set -> sorted list, datetime.time -> ISO string). The default returns the value unchanged.

Parameters:
valueobject

The current field value (already normalized/canonical).

Returns:
object

A JSON/YAML-safe value.

deserialize(value)[source]

Deserialize a value from dict form back to the field’s type.

Logical inverse of serialize. Called by from_dict() before setattr; the result is then passed through normalize and validate via __set__. The default returns the value unchanged.

Parameters:
valueobject

The value from the dict.

Returns:
object

The deserialized value, ready to be set on the instance.

to_argparse_kwargs(name, prefix='')[source]

Return kwargs dict for parser.add_argument().

The returned dict always contains a "flag" key with the full option string (e.g. "--search.n-sigma"). Pull it out before calling argparse:

kwargs = descriptor.to_argparse_kwargs(name, prefix)
flag = kwargs.pop("flag")
parser.add_argument(flag, **kwargs)

Override in subclasses to customize the argparse representation (add "choices", "nargs", "action", "metavar").

Parameters:
namestr

Field attribute name.

prefixstr, optional

Dot-separated prefix for nested configs (e.g. "search").

Returns:
dict
from_string(s)[source]

Parse a raw string into this field’s type.

Override in subclasses to coerce the raw string to the appropriate type for a particular ConfigField. The default implementation returns the unchanged string.

Called by __get__ when env is set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparse type= callable. The result is then passed to validate.

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

validate(value)[source]

Validate a value against this field’s constraints.

Called after normalize. Override in subclasses to enforce correct type or range of values. Raise TypeError for wrong type, and ValueError for out-of-range error. The base implementation accepts any value.

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

class cfx.List(default_value, doc, element_type=None, minlen=None, maxlen=None, static=False, env=None, transient=None)[source]

Bases: cfx.types.config_field.ConfigField

A field that validates list values.

Parameters:
default_valuelist or callable

Default list value or lazy factory returning a list.

docstr

Documentation.

element_typetype or None, optional

If provided, every element of the list must be an instance of this type. Default is None (no element-level type check).

minlenint or None, optional

Minimum number of elements. Default is None.

maxlenint or None, optional

Maximum number of elements. Default is None.

staticbool, optional

If True, the value is frozen at class-definition time. Default is False.

Raises:
TypeError

If the value is not a list, or contains elements of the wrong type when element_type is set.

ValueError

If the list length is outside [minlen, maxlen].

element_type = None
minlen = None
maxlen = None
normalize(value)[source]

Transform value to canonical form before validation and storage.

Called before validate in both __init__ (for non-callable defaults) and __set__. Must be idempotent: applying normalize twice yields the same result as applying it once.

Override in subclasses to coerce common input types to the field’s canonical type. Examples: str -> pathlib.Path, list -> tuple, angular wrap-around to [0, 360).

The default implementation returns the value unchanged.

Parameters:
valueobject

The raw value to normalize.

Returns:
object

The normalized value, ready to pass to validate.

serialize(value)[source]

Serialize value to a JSON/YAML-safe form for to_dict().

Override in subclasses for types that need a different on-disk representation (e.g. pathlib.Path -> str, set -> sorted list, datetime.time -> ISO string). The default returns the value unchanged.

Parameters:
valueobject

The current field value (already normalized/canonical).

Returns:
object

A JSON/YAML-safe value.

deserialize(value)[source]

Deserialize a value from dict form back to the field’s type.

Logical inverse of serialize. Called by from_dict() before setattr; the result is then passed through normalize and validate via __set__. The default returns the value unchanged.

Parameters:
valueobject

The value from the dict.

Returns:
object

The deserialized value, ready to be set on the instance.

to_argparse_kwargs(name, prefix='')[source]

Return kwargs dict for parser.add_argument().

The returned dict always contains a "flag" key with the full option string (e.g. "--search.n-sigma"). Pull it out before calling argparse:

kwargs = descriptor.to_argparse_kwargs(name, prefix)
flag = kwargs.pop("flag")
parser.add_argument(flag, **kwargs)

Override in subclasses to customize the argparse representation (add "choices", "nargs", "action", "metavar").

Parameters:
namestr

Field attribute name.

prefixstr, optional

Dot-separated prefix for nested configs (e.g. "search").

Returns:
dict
to_click_option(name, prefix='')[source]

Return a click.option() decorator for this field.

Override in subclasses to customize the click representation.

Parameters:
namestr

Field attribute name.

prefixstr, optional

Dot-separated prefix for nested configs.

Returns:
decorator

A click.option(...) decorator ready to stack on a command.

Raises:
ImportError

If click is not installed.

from_string(s)[source]

Parse a raw string into this field’s type.

Override in subclasses to coerce the raw string to the appropriate type for a particular ConfigField. The default implementation returns the unchanged string.

Called by __get__ when env is set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparse type= callable. The result is then passed to validate.

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

validate(value)[source]

Validate a value against this field’s constraints.

Called after normalize. Override in subclasses to enforce correct type or range of values. Raise TypeError for wrong type, and ValueError for out-of-range error. The base implementation accepts any value.

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

class cfx.Dict(default_value, doc, static=False, env=None, transient=None)[source]

Bases: cfx.types.config_field.ConfigField

A field that validates dict values.

Accepts any dict. Use this for free-form sub-structure that is too loosely typed to warrant a nested Config, but too structured to be a String.

Parameters:
default_valuedict or callable

Default dict value or lazy factory returning a dict.

docstr

Documentation.

staticbool, optional

If True, the value is frozen at class-definition time. Default is False.

Raises:
TypeError

If the value is not a dict.

from_string(s)[source]

Parse a raw string into this field’s type.

Override in subclasses to coerce the raw string to the appropriate type for a particular ConfigField. The default implementation returns the unchanged string.

Called by __get__ when env is set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparse type= callable. The result is then passed to validate.

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

to_string(value)[source]

Format a field value as a human-readable string for display.

Called by the display layer when rendering the config table. Override in subclasses to produce cleaner output than Python’s default str(). The default implementation returns str(value).

Parameters:
valueobject

The current field value.

Returns:
sstr

Display string for the value.

validate(value)[source]

Validate a value against this field’s constraints.

Called after normalize. Override in subclasses to enforce correct type or range of values. Raise TypeError for wrong type, and ValueError for out-of-range error. The base implementation accepts any value.

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

to_argparse_kwargs(name, prefix='')[source]

Return kwargs dict for parser.add_argument().

The returned dict always contains a "flag" key with the full option string (e.g. "--search.n-sigma"). Pull it out before calling argparse:

kwargs = descriptor.to_argparse_kwargs(name, prefix)
flag = kwargs.pop("flag")
parser.add_argument(flag, **kwargs)

Override in subclasses to customize the argparse representation (add "choices", "nargs", "action", "metavar").

Parameters:
namestr

Field attribute name.

prefixstr, optional

Dot-separated prefix for nested configs (e.g. "search").

Returns:
dict
class cfx.Date(default_value, doc, static=False, env=None, transient=None)[source]

Bases: cfx.types.config_field.ConfigField

A field that validates datetime.date values.

Parameters:
default_valuedatetime.date or callable

Default date value or lazy factory returning a datetime.date.

docstr

Documentation.

staticbool, optional

If True, the value is frozen at class-definition time. Default is False.

Raises:
TypeError

If the value is not a datetime.date.

normalize(value)[source]

Transform value to canonical form before validation and storage.

Called before validate in both __init__ (for non-callable defaults) and __set__. Must be idempotent: applying normalize twice yields the same result as applying it once.

Override in subclasses to coerce common input types to the field’s canonical type. Examples: str -> pathlib.Path, list -> tuple, angular wrap-around to [0, 360).

The default implementation returns the value unchanged.

Parameters:
valueobject

The raw value to normalize.

Returns:
object

The normalized value, ready to pass to validate.

validate(value)[source]

Validate a value against this field’s constraints.

Called after normalize. Override in subclasses to enforce correct type or range of values. Raise TypeError for wrong type, and ValueError for out-of-range error. The base implementation accepts any value.

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

serialize(value)[source]

Serialize value to a JSON/YAML-safe form for to_dict().

Override in subclasses for types that need a different on-disk representation (e.g. pathlib.Path -> str, set -> sorted list, datetime.time -> ISO string). The default returns the value unchanged.

Parameters:
valueobject

The current field value (already normalized/canonical).

Returns:
object

A JSON/YAML-safe value.

deserialize(value)[source]

Deserialize a value from dict form back to the field’s type.

Logical inverse of serialize. Called by from_dict() before setattr; the result is then passed through normalize and validate via __set__. The default returns the value unchanged.

Parameters:
valueobject

The value from the dict.

Returns:
object

The deserialized value, ready to be set on the instance.

from_string(s)[source]

Parse a raw string into this field’s type.

Override in subclasses to coerce the raw string to the appropriate type for a particular ConfigField. The default implementation returns the unchanged string.

Called by __get__ when env is set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparse type= callable. The result is then passed to validate.

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

to_string(value)[source]

Format a field value as a human-readable string for display.

Called by the display layer when rendering the config table. Override in subclasses to produce cleaner output than Python’s default str(). The default implementation returns str(value).

Parameters:
valueobject

The current field value.

Returns:
sstr

Display string for the value.

to_argparse_kwargs(name, prefix='')[source]

Return kwargs dict for parser.add_argument().

The returned dict always contains a "flag" key with the full option string (e.g. "--search.n-sigma"). Pull it out before calling argparse:

kwargs = descriptor.to_argparse_kwargs(name, prefix)
flag = kwargs.pop("flag")
parser.add_argument(flag, **kwargs)

Override in subclasses to customize the argparse representation (add "choices", "nargs", "action", "metavar").

Parameters:
namestr

Field attribute name.

prefixstr, optional

Dot-separated prefix for nested configs (e.g. "search").

Returns:
dict
class cfx.Time(default_value, doc, static=False, env=None, transient=None)[source]

Bases: cfx.types.config_field.ConfigField

A field that validates datetime.time values.

Parameters:
default_valuedatetime.time or callable

Default time value or lazy factory returning a datetime.time.

docstr

Documentation.

staticbool, optional

If True, the value is frozen at class-definition time. Default is False.

Raises:
TypeError

If the value is not a datetime.time.

normalize(value)[source]

Transform value to canonical form before validation and storage.

Called before validate in both __init__ (for non-callable defaults) and __set__. Must be idempotent: applying normalize twice yields the same result as applying it once.

Override in subclasses to coerce common input types to the field’s canonical type. Examples: str -> pathlib.Path, list -> tuple, angular wrap-around to [0, 360).

The default implementation returns the value unchanged.

Parameters:
valueobject

The raw value to normalize.

Returns:
object

The normalized value, ready to pass to validate.

validate(value)[source]

Validate a value against this field’s constraints.

Called after normalize. Override in subclasses to enforce correct type or range of values. Raise TypeError for wrong type, and ValueError for out-of-range error. The base implementation accepts any value.

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

serialize(value)[source]

Serialize value to a JSON/YAML-safe form for to_dict().

Override in subclasses for types that need a different on-disk representation (e.g. pathlib.Path -> str, set -> sorted list, datetime.time -> ISO string). The default returns the value unchanged.

Parameters:
valueobject

The current field value (already normalized/canonical).

Returns:
object

A JSON/YAML-safe value.

deserialize(value)[source]

Deserialize a value from dict form back to the field’s type.

Logical inverse of serialize. Called by from_dict() before setattr; the result is then passed through normalize and validate via __set__. The default returns the value unchanged.

Parameters:
valueobject

The value from the dict.

Returns:
object

The deserialized value, ready to be set on the instance.

from_string(s)[source]

Parse a raw string into this field’s type.

Override in subclasses to coerce the raw string to the appropriate type for a particular ConfigField. The default implementation returns the unchanged string.

Called by __get__ when env is set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparse type= callable. The result is then passed to validate.

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

to_string(value)[source]

Format a field value as a human-readable string for display.

Called by the display layer when rendering the config table. Override in subclasses to produce cleaner output than Python’s default str(). The default implementation returns str(value).

Parameters:
valueobject

The current field value.

Returns:
sstr

Display string for the value.

to_argparse_kwargs(name, prefix='')[source]

Return kwargs dict for parser.add_argument().

The returned dict always contains a "flag" key with the full option string (e.g. "--search.n-sigma"). Pull it out before calling argparse:

kwargs = descriptor.to_argparse_kwargs(name, prefix)
flag = kwargs.pop("flag")
parser.add_argument(flag, **kwargs)

Override in subclasses to customize the argparse representation (add "choices", "nargs", "action", "metavar").

Parameters:
namestr

Field attribute name.

prefixstr, optional

Dot-separated prefix for nested configs (e.g. "search").

Returns:
dict
class cfx.DateTime(default_value, doc, static=False, env=None, transient=None)[source]

Bases: cfx.types.config_field.ConfigField

A field that validates datetime.datetime values.

Parameters:
default_valuedatetime.datetime or callable

Default datetime value or lazy factory returning a datetime.datetime.

docstr

Documentation.

staticbool, optional

If True, the value is frozen at class-definition time. Default is False.

Raises:
TypeError

If the value is not a datetime.datetime.

normalize(value)[source]

Transform value to canonical form before validation and storage.

Called before validate in both __init__ (for non-callable defaults) and __set__. Must be idempotent: applying normalize twice yields the same result as applying it once.

Override in subclasses to coerce common input types to the field’s canonical type. Examples: str -> pathlib.Path, list -> tuple, angular wrap-around to [0, 360).

The default implementation returns the value unchanged.

Parameters:
valueobject

The raw value to normalize.

Returns:
object

The normalized value, ready to pass to validate.

validate(value)[source]

Validate a value against this field’s constraints.

Called after normalize. Override in subclasses to enforce correct type or range of values. Raise TypeError for wrong type, and ValueError for out-of-range error. The base implementation accepts any value.

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

serialize(value)[source]

Serialize value to a JSON/YAML-safe form for to_dict().

Override in subclasses for types that need a different on-disk representation (e.g. pathlib.Path -> str, set -> sorted list, datetime.time -> ISO string). The default returns the value unchanged.

Parameters:
valueobject

The current field value (already normalized/canonical).

Returns:
object

A JSON/YAML-safe value.

deserialize(value)[source]

Deserialize a value from dict form back to the field’s type.

Logical inverse of serialize. Called by from_dict() before setattr; the result is then passed through normalize and validate via __set__. The default returns the value unchanged.

Parameters:
valueobject

The value from the dict.

Returns:
object

The deserialized value, ready to be set on the instance.

from_string(s)[source]

Parse a raw string into this field’s type.

Override in subclasses to coerce the raw string to the appropriate type for a particular ConfigField. The default implementation returns the unchanged string.

Called by __get__ when env is set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparse type= callable. The result is then passed to validate.

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

to_string(value)[source]

Format a field value as a human-readable string for display.

Called by the display layer when rendering the config table. Override in subclasses to produce cleaner output than Python’s default str(). The default implementation returns str(value).

Parameters:
valueobject

The current field value.

Returns:
sstr

Display string for the value.

to_argparse_kwargs(name, prefix='')[source]

Return kwargs dict for parser.add_argument().

The returned dict always contains a "flag" key with the full option string (e.g. "--search.n-sigma"). Pull it out before calling argparse:

kwargs = descriptor.to_argparse_kwargs(name, prefix)
flag = kwargs.pop("flag")
parser.add_argument(flag, **kwargs)

Override in subclasses to customize the argparse representation (add "choices", "nargs", "action", "metavar").

Parameters:
namestr

Field attribute name.

prefixstr, optional

Dot-separated prefix for nested configs (e.g. "search").

Returns:
dict
class cfx.Alias(ref)[source]

A view field that delegates reads and writes to a dotpath on the bound config.

Declare Alias attributes on a ConfigView subclass to define which fields of the underlying config are exposed and under what names. The argument is either a FieldRef obtained by class-level attribute access on a Config class, or a plain dotpath string:

class CalibSummaryView(ConfigView):
    psf_kernel = Alias(PSFFittingConfig.kernel_estimate)  # preferred
    threshold  = Alias("detection.threshold")              # also works
Parameters:
refFieldRef or str

Path to the target field on the bound config. Pass a FieldRef (from class-level attribute access on a Config) to keep the path refactorable via IDE rename tools. A plain dotpath string is accepted for convenience.

__set_name__(owner, name)[source]
__get__(obj, objtype=None)[source]
__set__(obj, value)[source]
class cfx.Mirror(*refs)[source]

A config field that keeps multiple dotpaths in sync.

Declare a Mirror on a Config class to enforce that two or more fields always hold the same value. A write fans out to every path; a read asserts all paths agree and returns the shared value:

class SyncedConfig(Config, components=[CameraConfig, DetectorConfig]):
    gain = Mirror(CameraConfig.gain, DetectorConfig.gain)
Parameters:
*refsFieldRef or str

Dotpaths (relative to the config instance) that must stay in sync. Pass FieldRef objects obtained from class-level attribute access on a Config for refactorable, IDE-navigable paths.

__set_name__(owner, name)[source]
__get__(obj, objtype=None)[source]
__set__(obj, value)[source]
class cfx.AliasedView[source]

Bases: ConfigView

A self-contained view that owns its component instances.

Subclass AliasedView and pass components= to auto-generate Alias descriptors for every field in each component. By default each alias is prefixed with the component’s confid:

class CalibView(AliasedView, components=[PSFConfig, PhotoConfig]):
    pass

v = CalibView()
v.psf_kernel = 3.5   # writes through to v.psf.kernel_estimate

Supply aliases= to override the prefix for each component (use None for a flat, unprefixed namespace):

class CalibView(AliasedView,
                components=[PSFConfig, PhotoConfig],
                aliases=["psf", None]):
    pass

Name conflicts among auto-generated aliases raise ValueError at class-definition time.

Unlike ConfigView, an AliasedView is constructed with no arguments — it creates and owns a fresh instance of each component.

classmethod __init_subclass__(components=None, aliases=None, **kwargs)[source]
classmethod from_dict(d)[source]

Create a fresh view and apply field values from d.

Parameters:
ddict

Alias names and replacement values.

Returns:
viewAliasedView

A new view with d values applied.

class cfx.ConfigView(config)[source]

Base class for curated projections over a Config instance.

Subclass ConfigView and declare Alias attributes to expose a selected subset of fields from one or more configs under names that suit the consumer’s context. All reads and writes delegate to the bound config — the view itself holds no values:

class CalibSummaryView(ConfigView):
    psf_kernel = Alias(PSFFittingConfig.kernel_estimate)
    zero_point = Alias(PhotometryConfig.zero_point)

view = CalibSummaryView(pipeline.calibration)
view.psf_kernel           # reads pipeline.calibration.psf_fitting...
view.psf_kernel = 3.5     # writes through

Views can span multiple sub-configs by binding to a common parent:

class PipelineSummaryView(ConfigView):
    psf_kernel = Alias(CalibrationConfig.psf_fitting.kernel_estimate)
    threshold  = Alias(DetectionConfig.threshold)

view = PipelineSummaryView(pipeline_cfg)
Parameters:
configConfig

The config instance to bind to. All alias paths are resolved relative to this object.

classmethod __init_subclass__(**kwargs)[source]
to_dict()[source]

Return a plain dict of the aliased fields and their current values.

Returns:
ddict

Mapping of alias name to current value for every declared Alias.

classmethod from_dict(d, config)[source]

Bind config and apply values from d through the view’s aliases.

Parameters:
ddict

Alias names and replacement values.

configConfig

The config instance to bind and write into.

Returns:
viewConfigView

A bound view with d values applied.

__repr__()[source]
class cfx.FlatView[source]

Bases: AliasedView

An AliasedView with no component prefix.

Every component field is exposed directly by its own name. A ValueError is raised at class-definition time if two components share a field name:

class InstrumentView(
        FlatView,
        components=[
            CameraConfig,
            FilterConfig,
        ]):
    pass

v = InstrumentView()
v.gain = 2.0   # writes through to v.camera.gain
classmethod __init_subclass__(components=None, **kwargs)[source]