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¶
Raised when attempting to set a field on a frozen |
Classes¶
Base class for all user-defined configuration classes. |
|
Descriptor installed on a |
|
A reference to a field on a |
|
Base descriptor for a single configuration field. |
|
Placeholder returned by |
|
A field that accepts any value without validation. |
|
A field that validates string values. |
|
A field that validates integer values. |
|
A field that validates floating-point values. |
|
A field that validates numeric (int or float) values. |
|
A field that validates boolean values. |
|
A field whose value must be one of a fixed set of choices. |
|
A field whose value must be a subset of a fixed set of choices. |
|
A field that coerces and validates filesystem paths. |
|
A field for random-number-generator seeds. |
|
A field for a linear (min, max) numeric range. |
|
A field that validates list values. |
|
A field that validates dict values. |
|
A field that validates |
|
A field that validates |
|
A field that validates |
|
A view field that delegates reads and writes to a dotpath on the |
|
A config field that keeps multiple dotpaths in sync. |
|
A self-contained view that owns its component instances. |
|
Base class for curated projections over a |
|
An |
Functions¶
|
Declare an annotation-native config field. |
|
Instantiate the right |
Package Contents¶
- class cfx.Config(**kwargs)[source]¶
Base class for all user-defined configuration classes.
Subclass
Configand declareConfigFieldinstances as class attributes to define a configuration schema. Fields are validated on assignment, self-documenting via__str__, and composable via inheritance or thecomponents=keyword.- Parameters:
- **kwargs
object Initial field values passed as keyword arguments. Each keyword must match a declared field name and is validated on assignment.
- **kwargs
- Attributes:
- confid
str 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)getsconfid = "searchconfig"automatically.
- confid
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.
- 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, andfrom_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")
- values()[source]¶
Return the current values of all declared fields.
- Returns:
- values
list Current field values in declaration order.
- values
- items()[source]¶
Return (name, value) pairs for all declared fields.
- Returns:
- pairs
list[tuple] (field_name, current_value)pairs in declaration order.
- pairs
- update(mapping)[source]¶
Set multiple field values from a mapping.
Each key-value pair is set via
setattr, routing through the descriptor’svalidatemethod. Nested sub-configs can be updated by passing the confid as the key with adictvalue (which is applied recursively) or aConfiginstance (which replaces the sub-config entirely).
- freeze()[source]¶
Make this config instance read-only.
After calling
freeze, any attempt to set a field or replace a nested sub-config raisesFrozenConfigError. 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".
- copy(**overrides)[source]¶
Return a new instance with optionally overridden field values.
- Parameters:
- **overrides
object Field names and replacement values applied after copying all current field values.
- **overrides
- Returns:
- cfg
Config A new instance of the same class with the same field values, except where overridden.
- cfg
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.
- to_dict()[source]¶
Serialize this config to a plain
dict.- Returns:
- d
dict Mapping of field names to their current values. Nested
Configsub-objects are serialized recursively.pathlib.Pathvalues are serialized as strings so the result is always JSON/YAML/TOML-safe.
- d
- to_yaml()[source]¶
Serialize this config to a YAML string.
- Returns:
- yaml_str
str YAML representation of the config.
- yaml_str
- Raises:
- ImportError
If
pyyamlis not installed.
- classmethod add_arguments(parser, prefix='')[source]¶
Register all non-static fields as arguments on parser.
For nested configs the component’s
confidis used as the dot-notation prefix: fieldn_sigmain a sub-config withconfid = "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:
- parser
argparse.ArgumentParser The parser to register arguments on.
- prefix
str, optional Dot-separated prefix prepended to every flag name. Default
"".
- parser
- classmethod from_argparse(namespace)[source]¶
Build a
Configinstance from a parsed argparse namespace.If the namespace contains a
config_filevalue (registered byadd_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:
- namespace
argparse.Namespace Result of
parser.parse_args().
- namespace
- Returns:
- cfg
Config A new instance with values taken from the namespace. Fields absent from the namespace (value
None) keep their base defaults.
- cfg
- 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:
- decorator
callable A decorator that applies all
click.optiondecorators for this config’s fields to the target function.
- decorator
- Raises:
- ImportError
If
clickis not installed.
- exception cfx.FrozenConfigError[source]¶
Bases:
AttributeErrorRaised when attempting to set a field on a frozen
Configinstance.Inherits from
AttributeErrorso that standard attribute-protection machinery recognises it correctly.
- class cfx.ComponentRef(confid, cls)[source]¶
Descriptor installed on a
Configclass for each component slot.Installed automatically by
_ConfigTypeafter_nested_classesis built. Returns aFieldRefon class-level access so component paths can be used inAliasandMirrordeclarations. On instance access returns the stored sub-config instance as normal.- confid¶
- cls¶
- class cfx.FieldRef(path, resolved_cls)[source]¶
A reference to a field on a
Configclass.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
AttributeErrorimmediately, not at the first runtime access.Pass a
FieldReftoAliasorMirrorinstead 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 ...>
- 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 onConfigsubclasses.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_value
objectorcallable 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.- doc
str Human-readable description shown in
__str__tables and Jupyter_repr_html_output.- static
bool, optional If
Truethe value is frozen todefault_valueat class-definition time and cannot be changed on instances. Any attempted__set__raisesAttributeError. Default isFalse.- env
strorNone, 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.environis coerced by_from_env_strand then validated. The env value is not stored on the instance - it is re-read on every access, matching the behaviour of callable defaults.Nonemeans no environment variable is consulted. Default isNone.
- default_value
- Raises:
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
validatein 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. RaiseTypeErrorfor wrong type, andValueErrorfor out-of-range error. The base implementation accepts any value.- Parameters:
- value
object The normalized value to validate.
- value
- 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__whenenvis set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparsetype=callable. The result is then passed tovalidate.
- 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 returnsstr(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 byfrom_dict()beforesetattr; the result is then passed throughnormalizeandvalidatevia__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
Trueif an explicit value is stored on obj.Returns
Falsewhen 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 tounset. 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
clickis not installed.
- __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) andprivate_name(the name used to store the per-instance value ininstance.__dict__).
- __get__(obj, objtype)[source]¶
- __get__(obj: object, objtype: type) T
Return the field value for the owning instance.
If accessed on the class (
objisNone) returns aFieldRefpath proxy, enabling IDE-refactorable paths for use inAliasandMirrordeclarations.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
envis set and the variable is present inos.environdefaultval, called if callable, returned directly otherwise
- 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
Configsubclass. The concreteConfigFieldsubclass 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:
- Returns:
- spec
FieldSpec Placeholder resolved to a
ConfigFieldat class-definition time.
- spec
- 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 everyFieldSpecwith the appropriateConfigFieldsubclass before any instance is created.- default¶
- doc¶
- kwargs¶
- cfx.resolve_field_spec(name, spec, annotation)[source]¶
Instantiate the right
ConfigFieldsubclass for an annotation.Called by
Config.__init_subclass__for everyFieldSpecin the class body. Not part of the end-user API but importable for advanced use.- Parameters:
- Returns:
- field
ConfigField A fully constructed field descriptor.
- field
- Raises:
- TypeError
If the annotation cannot be mapped to a known
ConfigFieldtype.
- class cfx.Any(default_value, doc, static=False, env=None, transient=None)[source]¶
Bases:
cfx.types.config_field.ConfigFieldA field that accepts any value without validation.
Use this as an explicit escape hatch when validation is intentionally deferred to
Config.validateor handled externally. TheAnyname signals intent: the author has consciously opted out of field-level constraints.
- class cfx.String(default_value, doc, minsize=0, maxsize=None, predicate=None, static=False, env=None, transient=None)[source]¶
Bases:
cfx.types.config_field.ConfigFieldA field that validates string values.
- Parameters:
- default_value
strorcallable Default string value or lazy factory returning a
str.- doc
str Documentation.
- minsize
int, optional Minimum allowed string length. Default is
0.- maxsize
intorNone, optional Maximum allowed string length.
Nonemeans no upper limit. Default isNone.- predicate
callableorNone, optional Additional validation callable that accepts a
strand returnsTrueif the value is valid. Default isNone.- static
bool, optional If
True, the value is frozen at class-definition time. Default isFalse.
- default_value
- 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. RaiseTypeErrorfor wrong type, andValueErrorfor out-of-range error. The base implementation accepts any value.- Parameters:
- value
object The normalized value to validate.
- value
- 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.ConfigFieldA field that validates integer values.
- Parameters:
- default_value
intorcallable Default integer value or lazy factory returning an
int.- doc
str Documentation.
- minval
intorNone, optional Minimum allowed value (inclusive). Default is
None.- maxval
intorNone, optional Maximum allowed value (inclusive). Default is
None.- static
bool, optional If
True, the value is frozen at class-definition time. Default isFalse.- env
strorNone, optional Environment variable name. See
ConfigField.
- default_value
- 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__whenenvis set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparsetype=callable. The result is then passed tovalidate.
- 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. RaiseTypeErrorfor wrong type, andValueErrorfor out-of-range error. The base implementation accepts any value.- Parameters:
- value
object The normalized value to validate.
- value
- 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.ConfigFieldA field that validates floating-point values.
- Parameters:
- default_value
floatorcallable Default float value or lazy factory returning a
float.- doc
str Documentation.
- minval
floatorNone, optional Minimum allowed value (inclusive). Default is
None.- maxval
floatorNone, optional Maximum allowed value (inclusive). Default is
None.- static
bool, optional If
True, the value is frozen at class-definition time. Default isFalse.- env
strorNone, optional Environment variable name. See
ConfigField.
- default_value
- Raises:
- 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__whenenvis set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparsetype=callable. The result is then passed tovalidate.
- 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. RaiseTypeErrorfor wrong type, andValueErrorfor out-of-range error. The base implementation accepts any value.- Parameters:
- value
object The normalized value to validate.
- value
- 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.ConfigFieldA 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
IntorFloat.- Parameters:
- default_value
numbers.Numberorcallable Default numeric value or lazy factory returning a number.
- doc
str Documentation.
- minval
numbers.NumberorNone, optional Minimum allowed value (inclusive). Default is
None.- maxval
numbers.NumberorNone, optional Maximum allowed value (inclusive). Default is
None.- static
bool, optional If
True, the value is frozen at class-definition time. Default isFalse.
- default_value
- 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__whenenvis set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparsetype=callable. The result is then passed tovalidate.
- 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. RaiseTypeErrorfor wrong type, andValueErrorfor out-of-range error. The base implementation accepts any value.- Parameters:
- value
object The normalized value to validate.
- value
- 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.ConfigFieldA field that validates boolean values.
- Parameters:
- 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__whenenvis set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparsetype=callable. The result is then passed tovalidate.
- 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. RaiseTypeErrorfor wrong type, andValueErrorfor out-of-range error. The base implementation accepts any value.- Parameters:
- value
object The normalized value to validate.
- value
- 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
clickis not installed.
- class cfx.Options(options, doc, default_value=None, static=False, env=None, transient=None)[source]¶
Bases:
cfx.types.config_field.ConfigFieldA field whose value must be one of a fixed set of choices.
- Parameters:
- options
tupleorlist Allowed values. The first element is used as the default unless
default_valueis provided.- doc
str Documentation.
- default_value
object, optional Default value. Must be a member of
options. Defaults tooptions[0].- static
bool, optional If
True, the value is frozen at class-definition time. Default isFalse.
- options
- 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. RaiseTypeErrorfor wrong type, andValueErrorfor out-of-range error. The base implementation accepts any value.- Parameters:
- value
object The normalized value to validate.
- value
- 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
clickis not installed.
- class cfx.MultiOptions(options, doc, default_value=None, static=False, env=None, transient=None)[source]¶
Bases:
cfx.types.config_field.ConfigFieldA field whose value must be a subset of a fixed set of choices.
- Parameters:
- Raises:
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
validatein 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. RaiseTypeErrorfor wrong type, andValueErrorfor out-of-range error. The base implementation accepts any value.- Parameters:
- value
object The normalized value to validate.
- value
- 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 byfrom_dict()beforesetattr; the result is then passed throughnormalizeandvalidatevia__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__whenenvis set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparsetype=callable. The result is then passed tovalidate.
- 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 returnsstr(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
clickis not installed.
- class cfx.Path(default_value, doc, must_exist=False, static=False, env=None, transient=None)[source]¶
Bases:
cfx.types.config_field.ConfigFieldA field that coerces and validates filesystem paths.
Accepts
strorpathlib.Pathvalues and stores them aspathlib.Pathobjects.- Parameters:
- default_value
str,pathlib.Path, orcallable Default path value or lazy factory. Strings are coerced to
pathlib.Pathon assignment.- doc
str Documentation.
- must_exist
bool, optional If
True, raisesValueErrorwhen the path does not exist on the filesystem at the time of assignment. Default isFalse.- static
bool, optional If
True, the value is frozen at class-definition time. Default isFalse.
- default_value
- Raises:
- TypeError
If the value cannot be coerced to a
pathlib.Path.- ValueError
If
must_existisTrueand the path does not exist.
- must_exist = False¶
- normalize(value)[source]¶
Transform value to canonical form before validation and storage.
Called before
validatein 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. RaiseTypeErrorfor wrong type, andValueErrorfor out-of-range error. The base implementation accepts any value.- Parameters:
- value
object The normalized value to validate.
- value
- 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 byfrom_dict()beforesetattr; the result is then passed throughnormalizeandvalidatevia__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__whenenvis set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparsetype=callable. The result is then passed tovalidate.
- 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 returnsstr(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.ConfigFieldA field for random-number-generator seeds.
Accepts an
intorNone. A value ofNonesignals that the seed should be chosen randomly at runtime, distinct from any specific integer seed including zero.- Parameters:
- Raises:
- 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__whenenvis set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparsetype=callable. The result is then passed tovalidate.
- 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. RaiseTypeErrorfor wrong type, andValueErrorfor out-of-range error. The base implementation accepts any value.- Parameters:
- value
object The normalized value to validate.
- value
- 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.ConfigFieldA field for a linear (min, max) numeric range.
Stores a two-element tuple
(min, max)and validates thatmin < 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:
- 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
validatein 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 byfrom_dict()beforesetattr; the result is then passed throughnormalizeandvalidatevia__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__whenenvis set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparsetype=callable. The result is then passed tovalidate.
- 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. RaiseTypeErrorfor wrong type, andValueErrorfor out-of-range error. The base implementation accepts any value.- Parameters:
- value
object The normalized value to validate.
- value
- 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.ConfigFieldA field that validates list values.
- Parameters:
- default_value
listorcallable Default list value or lazy factory returning a
list.- doc
str Documentation.
- element_type
typeorNone, optional If provided, every element of the list must be an instance of this type. Default is
None(no element-level type check).- minlen
intorNone, optional Minimum number of elements. Default is
None.- maxlen
intorNone, optional Maximum number of elements. Default is
None.- static
bool, optional If
True, the value is frozen at class-definition time. Default isFalse.
- default_value
- Raises:
- TypeError
If the value is not a
list, or contains elements of the wrong type whenelement_typeis 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
validatein 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 byfrom_dict()beforesetattr; the result is then passed throughnormalizeandvalidatevia__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
clickis 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__whenenvis set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparsetype=callable. The result is then passed tovalidate.
- 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. RaiseTypeErrorfor wrong type, andValueErrorfor out-of-range error. The base implementation accepts any value.- Parameters:
- value
object The normalized value to validate.
- value
- 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.ConfigFieldA field that validates dict values.
Accepts any
dict. Use this for free-form sub-structure that is too loosely typed to warrant a nestedConfig, but too structured to be aString.- Parameters:
- 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__whenenvis set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparsetype=callable. The result is then passed tovalidate.
- 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 returnsstr(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. RaiseTypeErrorfor wrong type, andValueErrorfor out-of-range error. The base implementation accepts any value.- Parameters:
- value
object The normalized value to validate.
- value
- 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.ConfigFieldA field that validates
datetime.datevalues.- Parameters:
- default_value
datetime.dateorcallable Default date value or lazy factory returning a
datetime.date.- doc
str Documentation.
- static
bool, optional If
True, the value is frozen at class-definition time. Default isFalse.
- default_value
- Raises:
- TypeError
If the value is not a
datetime.date.
- normalize(value)[source]¶
Transform value to canonical form before validation and storage.
Called before
validatein 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. RaiseTypeErrorfor wrong type, andValueErrorfor out-of-range error. The base implementation accepts any value.- Parameters:
- value
object The normalized value to validate.
- value
- 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 byfrom_dict()beforesetattr; the result is then passed throughnormalizeandvalidatevia__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__whenenvis set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparsetype=callable. The result is then passed tovalidate.
- 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 returnsstr(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.ConfigFieldA field that validates
datetime.timevalues.- Parameters:
- default_value
datetime.timeorcallable Default time value or lazy factory returning a
datetime.time.- doc
str Documentation.
- static
bool, optional If
True, the value is frozen at class-definition time. Default isFalse.
- default_value
- Raises:
- TypeError
If the value is not a
datetime.time.
- normalize(value)[source]¶
Transform value to canonical form before validation and storage.
Called before
validatein 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. RaiseTypeErrorfor wrong type, andValueErrorfor out-of-range error. The base implementation accepts any value.- Parameters:
- value
object The normalized value to validate.
- value
- 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 byfrom_dict()beforesetattr; the result is then passed throughnormalizeandvalidatevia__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__whenenvis set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparsetype=callable. The result is then passed tovalidate.
- 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 returnsstr(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.ConfigFieldA field that validates
datetime.datetimevalues.- Parameters:
- default_value
datetime.datetimeorcallable Default datetime value or lazy factory returning a
datetime.datetime.- doc
str Documentation.
- static
bool, optional If
True, the value is frozen at class-definition time. Default isFalse.
- default_value
- Raises:
- TypeError
If the value is not a
datetime.datetime.
- normalize(value)[source]¶
Transform value to canonical form before validation and storage.
Called before
validatein 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. RaiseTypeErrorfor wrong type, andValueErrorfor out-of-range error. The base implementation accepts any value.- Parameters:
- value
object The normalized value to validate.
- value
- 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 byfrom_dict()beforesetattr; the result is then passed throughnormalizeandvalidatevia__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__whenenvis set and the variable is present in the environment but the instance has no explicitly stored value, and by the CLI integration as the argparsetype=callable. The result is then passed tovalidate.
- 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 returnsstr(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
Aliasattributes on aConfigViewsubclass to define which fields of the underlying config are exposed and under what names. The argument is either aFieldRefobtained by class-level attribute access on aConfigclass, or a plain dotpath string:class CalibSummaryView(ConfigView): psf_kernel = Alias(PSFFittingConfig.kernel_estimate) # preferred threshold = Alias("detection.threshold") # also works
- Parameters:
- class cfx.Mirror(*refs)[source]¶
A config field that keeps multiple dotpaths in sync.
Declare a
Mirroron aConfigclass 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:
- class cfx.AliasedView[source]¶
Bases:
ConfigViewA self-contained view that owns its component instances.
Subclass
AliasedViewand passcomponents=to auto-generateAliasdescriptors for every field in each component. By default each alias is prefixed with the component’sconfid: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 (useNonefor a flat, unprefixed namespace):class CalibView(AliasedView, components=[PSFConfig, PhotoConfig], aliases=["psf", None]): pass
Name conflicts among auto-generated aliases raise
ValueErrorat class-definition time.Unlike
ConfigView, anAliasedViewis constructed with no arguments — it creates and owns a fresh instance of each component.- classmethod from_dict(d)[source]¶
Create a fresh view and apply field values from d.
- Parameters:
- d
dict Alias names and replacement values.
- d
- Returns:
- view
AliasedView A new view with d values applied.
- view
- class cfx.ConfigView(config)[source]¶
Base class for curated projections over a
Configinstance.Subclass
ConfigViewand declareAliasattributes 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:
- config
Config The config instance to bind to. All alias paths are resolved relative to this object.
- config
- classmethod from_dict(d, config)[source]¶
Bind config and apply values from d through the view’s aliases.
- Parameters:
- Returns:
- view
ConfigView A bound view with d values applied.
- view
- class cfx.FlatView[source]¶
Bases:
AliasedViewAn
AliasedViewwith no component prefix.Every component field is exposed directly by its own name. A
ValueErroris 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