cfx.types¶
cfx field types and view field descriptors.
Submodules¶
Classes¶
Base descriptor for a single configuration field. |
|
Placeholder returned by |
|
A view field that delegates reads and writes to a dotpath on the |
|
A field that accepts any value without validation. |
|
A field that validates boolean values. |
|
A field that validates |
|
A field that validates |
|
A field that validates dict values. |
|
A field that validates floating-point values. |
|
A field that validates integer values. |
|
A field that validates list values. |
|
A config field that keeps multiple dotpaths in sync. |
|
A field whose value must be a subset of a fixed set of choices. |
|
A field whose value must be one of a fixed set of choices. |
|
A field that coerces and validates filesystem paths. |
|
A field for a linear (min, max) numeric range. |
|
A field that validates numeric (int or float) values. |
|
A field for random-number-generator seeds. |
|
A field that validates string values. |
|
A field that validates |
Functions¶
|
Declare an annotation-native config field. |
|
Instantiate the right |
Package Contents¶
- class cfx.types.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.types.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.types.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.types.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.types.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:
- ref
FieldReforstr Path to the target field on the bound config. Pass a
FieldRef(from class-level attribute access on aConfig) to keep the path refactorable via IDE rename tools. A plain dotpath string is accepted for convenience.
- ref
- class cfx.types.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.types.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.types.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.types.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.types.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.types.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.types.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.types.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.types.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:
- *refs
FieldReforstr Dotpaths (relative to the config instance) that must stay in sync. Pass
FieldRefobjects obtained from class-level attribute access on aConfigfor refactorable, IDE-navigable paths.
- *refs
- class cfx.types.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.types.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.types.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.types.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.types.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.types.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.types.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.types.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