cfx.config¶
Core Config class.
This module provides Config, the base class that all user-defined
configuration classes inherit from. Field collection and component wiring
happen in Config.__init_subclass__, which runs at class-definition time for
every subclass.
Exceptions¶
Raised when attempting to set a field on a frozen |
Classes¶
Base class for all user-defined configuration classes. |
Module Contents¶
- exception cfx.config.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.config.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.