cfx.types

cfx field types and view field descriptors.

Submodules

Classes

ConfigField

Base descriptor for a single configuration field.

FieldSpec

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

Alias

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

Any

A field that accepts any value without validation.

Bool

A field that validates boolean values.

Date

A field that validates datetime.date values.

DateTime

A field that validates datetime.datetime values.

Dict

A field that validates dict values.

Float

A field that validates floating-point values.

Int

A field that validates integer values.

List

A field that validates list values.

Mirror

A config field that keeps multiple dotpaths in sync.

MultiOptions

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

Options

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

Path

A field that coerces and validates filesystem paths.

Range

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

Scalar

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

Seed

A field for random-number-generator seeds.

String

A field that validates string values.

Time

A field that validates datetime.time values.

Functions

Field(default[, doc])

Declare an annotation-native config field.

resolve_field_spec(name, spec, annotation)

Instantiate the right ConfigField subclass for an annotation.

Package Contents

class cfx.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 on Config subclasses.

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

Parameters:
default_valueobject or callable

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

docstr

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

staticbool, optional

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

envstr or None, optional

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

Raises:
TypeError

If default_value (when not callable) fails validate.

ValueError

If default_value (when not callable) fails validate.

Examples

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

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

normalize(value)[source]

Transform value to canonical form before validation and storage.

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

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

The default implementation returns the value unchanged.

Parameters:
valueobject

The raw value to normalize.

Returns:
object

The normalized value, ready to pass to validate.

validate(value)[source]

Validate a value against this field’s constraints.

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

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

from_string(s)[source]

Parse a raw string into this field’s type.

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

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

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

to_string(value)[source]

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

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

Parameters:
valueobject

The current field value.

Returns:
sstr

Display string for the value.

serialize(value)[source]

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

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

Parameters:
valueobject

The current field value (already normalized/canonical).

Returns:
object

A JSON/YAML-safe value.

deserialize(value)[source]

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

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

Parameters:
valueobject

The value from the dict.

Returns:
object

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

is_set(obj)[source]

Return True if an explicit value is stored on obj.

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

Parameters:
objConfig

Instance to check.

unset(obj)[source]

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

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

Parameters:
objConfig

Instance to modify.

reset(obj, value=None)[source]

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

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

Parameters:
objConfig

Instance to modify.

valueobject, optional

New value. If None, reverts to default.

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

Return kwargs dict for parser.add_argument().

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

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

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

Parameters:
namestr

Field attribute name.

prefixstr, optional

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

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

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

Override in subclasses to customize the click representation.

Parameters:
namestr

Field attribute name.

prefixstr, optional

Dot-separated prefix for nested configs.

Returns:
decorator

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

Raises:
ImportError

If click is not installed.

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

Record the attribute name assigned by the owning class.

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

Parameters:
ownertype

The class that owns this descriptor.

namestr

The attribute name under which this descriptor was assigned.

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

Return the field value for the owning instance.

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

For static fields, always returns defaultval.

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

  • explicit assignment (stored on the instance)

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

  • defaultval, called if callable, returned directly otherwise

Parameters:
objConfig or None

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

objtypetype, optional

The owning class.

Returns:
valueobject

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

__set__(obj, value)[source]

Set the field value on the owning instance.

Full pipeline: normalize -> validate -> store.

Parameters:
objConfig

The owning instance.

valueobject

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

Raises:
AttributeError

If the field is declared static=True.

TypeError

If the value fails validate.

ValueError

If the value fails validate.

cfx.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 Config subclass. The concrete ConfigField subclass is inferred from the annotation at class-definition time:

from typing import Literal
from cfx import Config, Field

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

Callable defaults are supported for computed fields:

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

Default value or lazy factory accepting the owning instance.

docstr, optional

Human-readable description shown in display tables.

**kwargs

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

Returns:
specFieldSpec

Placeholder resolved to a ConfigField at class-definition time.

class cfx.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 every FieldSpec with the appropriate ConfigField subclass before any instance is created.

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

Instantiate the right ConfigField subclass for an annotation.

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

Parameters:
namestr

The attribute name (used in error messages).

specFieldSpec

The placeholder carrying default, doc, and extra kwargs.

annotationtype

The resolved type annotation for this attribute.

Returns:
fieldConfigField

A fully constructed field descriptor.

Raises:
TypeError

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

class cfx.types.Alias(ref)[source]

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

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

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

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

__set_name__(owner, name)[source]
__get__(obj, objtype=None)[source]
__set__(obj, value)[source]
class cfx.types.Any(default_value, doc, static=False, env=None, transient=None)[source]

Bases: cfx.types.config_field.ConfigField

A field that accepts any value without validation.

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

Parameters:
default_valueobject or callable

Default value or lazy factory.

docstr

Documentation.

staticbool, optional

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

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

Bases: cfx.types.config_field.ConfigField

A field that validates boolean values.

Parameters:
default_valuebool or callable

Default boolean value or lazy factory returning a bool.

docstr

Documentation.

staticbool, optional

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

Raises:
TypeError

If the value is not a bool.

from_string(s)[source]

Parse a raw string into this field’s type.

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

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

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

validate(value)[source]

Validate a value against this field’s constraints.

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

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

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

Return kwargs dict for parser.add_argument().

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

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

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

Parameters:
namestr

Field attribute name.

prefixstr, optional

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

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

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

Override in subclasses to customize the click representation.

Parameters:
namestr

Field attribute name.

prefixstr, optional

Dot-separated prefix for nested configs.

Returns:
decorator

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

Raises:
ImportError

If click is not installed.

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

Bases: cfx.types.config_field.ConfigField

A field that validates datetime.date values.

Parameters:
default_valuedatetime.date or callable

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

docstr

Documentation.

staticbool, optional

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

Raises:
TypeError

If the value is not a datetime.date.

normalize(value)[source]

Transform value to canonical form before validation and storage.

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

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

The default implementation returns the value unchanged.

Parameters:
valueobject

The raw value to normalize.

Returns:
object

The normalized value, ready to pass to validate.

validate(value)[source]

Validate a value against this field’s constraints.

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

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

serialize(value)[source]

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

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

Parameters:
valueobject

The current field value (already normalized/canonical).

Returns:
object

A JSON/YAML-safe value.

deserialize(value)[source]

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

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

Parameters:
valueobject

The value from the dict.

Returns:
object

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

from_string(s)[source]

Parse a raw string into this field’s type.

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

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

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

to_string(value)[source]

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

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

Parameters:
valueobject

The current field value.

Returns:
sstr

Display string for the value.

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

Return kwargs dict for parser.add_argument().

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

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

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

Parameters:
namestr

Field attribute name.

prefixstr, optional

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

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

Bases: cfx.types.config_field.ConfigField

A field that validates datetime.datetime values.

Parameters:
default_valuedatetime.datetime or callable

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

docstr

Documentation.

staticbool, optional

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

Raises:
TypeError

If the value is not a datetime.datetime.

normalize(value)[source]

Transform value to canonical form before validation and storage.

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

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

The default implementation returns the value unchanged.

Parameters:
valueobject

The raw value to normalize.

Returns:
object

The normalized value, ready to pass to validate.

validate(value)[source]

Validate a value against this field’s constraints.

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

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

serialize(value)[source]

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

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

Parameters:
valueobject

The current field value (already normalized/canonical).

Returns:
object

A JSON/YAML-safe value.

deserialize(value)[source]

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

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

Parameters:
valueobject

The value from the dict.

Returns:
object

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

from_string(s)[source]

Parse a raw string into this field’s type.

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

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

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

to_string(value)[source]

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

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

Parameters:
valueobject

The current field value.

Returns:
sstr

Display string for the value.

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

Return kwargs dict for parser.add_argument().

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

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

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

Parameters:
namestr

Field attribute name.

prefixstr, optional

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

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

Bases: cfx.types.config_field.ConfigField

A field that validates dict values.

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

Parameters:
default_valuedict or callable

Default dict value or lazy factory returning a dict.

docstr

Documentation.

staticbool, optional

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

Raises:
TypeError

If the value is not a dict.

from_string(s)[source]

Parse a raw string into this field’s type.

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

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

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

to_string(value)[source]

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

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

Parameters:
valueobject

The current field value.

Returns:
sstr

Display string for the value.

validate(value)[source]

Validate a value against this field’s constraints.

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

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

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

Return kwargs dict for parser.add_argument().

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

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

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

Parameters:
namestr

Field attribute name.

prefixstr, optional

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

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

Bases: cfx.types.config_field.ConfigField

A field that validates floating-point values.

Parameters:
default_valuefloat or callable

Default float value or lazy factory returning a float.

docstr

Documentation.

minvalfloat or None, optional

Minimum allowed value (inclusive). Default is None.

maxvalfloat or None, optional

Maximum allowed value (inclusive). Default is None.

staticbool, optional

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

envstr or None, optional

Environment variable name. See ConfigField.

Raises:
TypeError

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

ValueError

If the value is outside [minval, maxval].

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

Parse a raw string into this field’s type.

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

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

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

validate(value)[source]

Validate a value against this field’s constraints.

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

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

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

Bases: cfx.types.config_field.ConfigField

A field that validates integer values.

Parameters:
default_valueint or callable

Default integer value or lazy factory returning an int.

docstr

Documentation.

minvalint or None, optional

Minimum allowed value (inclusive). Default is None.

maxvalint or None, optional

Maximum allowed value (inclusive). Default is None.

staticbool, optional

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

envstr or None, optional

Environment variable name. See ConfigField.

Raises:
TypeError

If the value is not an int.

ValueError

If the value is outside [minval, maxval].

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

Parse a raw string into this field’s type.

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

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

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

validate(value)[source]

Validate a value against this field’s constraints.

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

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

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

Bases: cfx.types.config_field.ConfigField

A field that validates list values.

Parameters:
default_valuelist or callable

Default list value or lazy factory returning a list.

docstr

Documentation.

element_typetype or None, optional

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

minlenint or None, optional

Minimum number of elements. Default is None.

maxlenint or None, optional

Maximum number of elements. Default is None.

staticbool, optional

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

Raises:
TypeError

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

ValueError

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

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

Transform value to canonical form before validation and storage.

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

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

The default implementation returns the value unchanged.

Parameters:
valueobject

The raw value to normalize.

Returns:
object

The normalized value, ready to pass to validate.

serialize(value)[source]

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

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

Parameters:
valueobject

The current field value (already normalized/canonical).

Returns:
object

A JSON/YAML-safe value.

deserialize(value)[source]

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

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

Parameters:
valueobject

The value from the dict.

Returns:
object

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

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

Return kwargs dict for parser.add_argument().

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

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

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

Parameters:
namestr

Field attribute name.

prefixstr, optional

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

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

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

Override in subclasses to customize the click representation.

Parameters:
namestr

Field attribute name.

prefixstr, optional

Dot-separated prefix for nested configs.

Returns:
decorator

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

Raises:
ImportError

If click is not installed.

from_string(s)[source]

Parse a raw string into this field’s type.

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

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

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

validate(value)[source]

Validate a value against this field’s constraints.

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

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

class cfx.types.Mirror(*refs)[source]

A config field that keeps multiple dotpaths in sync.

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

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

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

__set_name__(owner, name)[source]
__get__(obj, objtype=None)[source]
__set__(obj, value)[source]
class cfx.types.MultiOptions(options, doc, default_value=None, static=False, env=None, transient=None)[source]

Bases: cfx.types.config_field.ConfigField

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

Parameters:
optionstuple or list

Full set of allowed values.

docstr

Documentation.

default_valueset or frozenset, optional

Default selection. Defaults to an empty set.

staticbool, optional

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

Raises:
TypeError

If the value is not a set or frozenset.

ValueError

If the value contains elements not in options.

Examples

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

Transform value to canonical form before validation and storage.

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

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

The default implementation returns the value unchanged.

Parameters:
valueobject

The raw value to normalize.

Returns:
object

The normalized value, ready to pass to validate.

validate(value)[source]

Validate a value against this field’s constraints.

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

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

serialize(value)[source]

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

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

Parameters:
valueobject

The current field value (already normalized/canonical).

Returns:
object

A JSON/YAML-safe value.

deserialize(value)[source]

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

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

Parameters:
valueobject

The value from the dict.

Returns:
object

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

from_string(s)[source]

Parse a raw string into this field’s type.

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

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

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

to_string(value)[source]

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

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

Parameters:
valueobject

The current field value.

Returns:
sstr

Display string for the value.

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

Return kwargs dict for parser.add_argument().

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

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

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

Parameters:
namestr

Field attribute name.

prefixstr, optional

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

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

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

Override in subclasses to customize the click representation.

Parameters:
namestr

Field attribute name.

prefixstr, optional

Dot-separated prefix for nested configs.

Returns:
decorator

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

Raises:
ImportError

If click is not installed.

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

Bases: cfx.types.config_field.ConfigField

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

Parameters:
optionstuple or list

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

docstr

Documentation.

default_valueobject, optional

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

staticbool, optional

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

Raises:
ValueError

If the value being set is not in options.

Examples

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

Validate a value against this field’s constraints.

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

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

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

Return kwargs dict for parser.add_argument().

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

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

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

Parameters:
namestr

Field attribute name.

prefixstr, optional

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

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

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

Override in subclasses to customize the click representation.

Parameters:
namestr

Field attribute name.

prefixstr, optional

Dot-separated prefix for nested configs.

Returns:
decorator

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

Raises:
ImportError

If click is not installed.

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

Bases: cfx.types.config_field.ConfigField

A field that coerces and validates filesystem paths.

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

Parameters:
default_valuestr, pathlib.Path, or callable

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

docstr

Documentation.

must_existbool, optional

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

staticbool, optional

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

Raises:
TypeError

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

ValueError

If must_exist is True and the path does not exist.

must_exist = False
normalize(value)[source]

Transform value to canonical form before validation and storage.

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

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

The default implementation returns the value unchanged.

Parameters:
valueobject

The raw value to normalize.

Returns:
object

The normalized value, ready to pass to validate.

validate(value)[source]

Validate a value against this field’s constraints.

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

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

serialize(value)[source]

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

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

Parameters:
valueobject

The current field value (already normalized/canonical).

Returns:
object

A JSON/YAML-safe value.

deserialize(value)[source]

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

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

Parameters:
valueobject

The value from the dict.

Returns:
object

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

from_string(s)[source]

Parse a raw string into this field’s type.

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

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

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

to_string(value)[source]

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

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

Parameters:
valueobject

The current field value.

Returns:
sstr

Display string for the value.

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

Return kwargs dict for parser.add_argument().

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

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

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

Parameters:
namestr

Field attribute name.

prefixstr, optional

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

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

Bases: cfx.types.config_field.ConfigField

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

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

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

Default (min, max) tuple or lazy factory.

docstr

Documentation.

staticbool, optional

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

Raises:
TypeError

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

ValueError

If min >= max.

normalize(value)[source]

Transform value to canonical form before validation and storage.

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

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

The default implementation returns the value unchanged.

Parameters:
valueobject

The raw value to normalize.

Returns:
object

The normalized value, ready to pass to validate.

serialize(value)[source]

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

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

Parameters:
valueobject

The current field value (already normalized/canonical).

Returns:
object

A JSON/YAML-safe value.

deserialize(value)[source]

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

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

Parameters:
valueobject

The value from the dict.

Returns:
object

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

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

Return kwargs dict for parser.add_argument().

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

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

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

Parameters:
namestr

Field attribute name.

prefixstr, optional

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

Returns:
dict
from_string(s)[source]

Parse a raw string into this field’s type.

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

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

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

validate(value)[source]

Validate a value against this field’s constraints.

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

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

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

Bases: cfx.types.config_field.ConfigField

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

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

Parameters:
default_valuenumbers.Number or callable

Default numeric value or lazy factory returning a number.

docstr

Documentation.

minvalnumbers.Number or None, optional

Minimum allowed value (inclusive). Default is None.

maxvalnumbers.Number or None, optional

Maximum allowed value (inclusive). Default is None.

staticbool, optional

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

Raises:
TypeError

If the value is not a numbers.Number.

ValueError

If the value is outside [minval, maxval].

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

Parse a raw string into this field’s type.

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

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

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

validate(value)[source]

Validate a value against this field’s constraints.

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

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

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

Bases: cfx.types.config_field.ConfigField

A field for random-number-generator seeds.

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

Parameters:
default_valueint, None, or callable

Default seed value or lazy factory.

docstr

Documentation.

staticbool, optional

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

Raises:
TypeError

If the value is not an int or None.

from_string(s)[source]

Parse a raw string into this field’s type.

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

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

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

validate(value)[source]

Validate a value against this field’s constraints.

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

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

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

Return kwargs dict for parser.add_argument().

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

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

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

Parameters:
namestr

Field attribute name.

prefixstr, optional

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

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

Bases: cfx.types.config_field.ConfigField

A field that validates string values.

Parameters:
default_valuestr or callable

Default string value or lazy factory returning a str.

docstr

Documentation.

minsizeint, optional

Minimum allowed string length. Default is 0.

maxsizeint or None, optional

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

predicatecallable or None, optional

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

staticbool, optional

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

Raises:
TypeError

If the value is not a str.

ValueError

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

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

Validate a value against this field’s constraints.

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

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

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

Bases: cfx.types.config_field.ConfigField

A field that validates datetime.time values.

Parameters:
default_valuedatetime.time or callable

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

docstr

Documentation.

staticbool, optional

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

Raises:
TypeError

If the value is not a datetime.time.

normalize(value)[source]

Transform value to canonical form before validation and storage.

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

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

The default implementation returns the value unchanged.

Parameters:
valueobject

The raw value to normalize.

Returns:
object

The normalized value, ready to pass to validate.

validate(value)[source]

Validate a value against this field’s constraints.

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

Parameters:
valueobject

The normalized value to validate.

Raises:
TypeError

If the value has the wrong type.

ValueError

If the value is outside the allowed range or set.

serialize(value)[source]

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

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

Parameters:
valueobject

The current field value (already normalized/canonical).

Returns:
object

A JSON/YAML-safe value.

deserialize(value)[source]

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

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

Parameters:
valueobject

The value from the dict.

Returns:
object

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

from_string(s)[source]

Parse a raw string into this field’s type.

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

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

Parameters:
sstr

Raw string value.

Returns:
valueobject

The coerced value, ready to pass to validate.

to_string(value)[source]

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

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

Parameters:
valueobject

The current field value.

Returns:
sstr

Display string for the value.

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

Return kwargs dict for parser.add_argument().

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

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

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

Parameters:
namestr

Field attribute name.

prefixstr, optional

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

Returns:
dict