Skip to content

Settings

settings

Info pydantic-model

Bases: SettingMixin, BaseModel

Info for a KCell.

validate_assignment is intentionally off: combined with a model_validator(mode="before") it would re-run validation against the entire extras dict on every per-field write, which historically silently coerced previously-stored values via clean_value() (see #944). Per-write validation is handled in __setattr__ and only inspects the new value.

Validators:

Source code in kfactory/settings.py
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
class Info(SettingMixin, BaseModel, extra="allow"):
    """Info for a KCell.

    `validate_assignment` is intentionally off: combined with a
    `model_validator(mode="before")` it would re-run validation against the
    entire extras dict on every per-field write, which historically silently
    coerced previously-stored values via `clean_value()` (see #944). Per-write
    validation is handled in `__setattr__` and only inspects the new value.
    """

    def __init__(self, **kwargs: Any) -> None:
        """Initialize the settings."""
        super().__init__(**kwargs)

    @model_validator(mode="before")
    @classmethod
    def restrict_types(cls, data: dict[str, MetaData]) -> dict[str, MetaData]:
        """Restrict the types of the settings (runs at construction only)."""
        for name, value in data.items():
            data[name] = cls._check_value(name, value)
        return data

    @staticmethod
    def _check_value(name: str, value: MetaData) -> MetaData:
        try:
            return check_metadata_type(value)
        except ValueError as e:
            raise ValueError(
                "Values of the info dict only support int, float, string, "
                "tuple, list, dict or None."
                f"{name}: {value}, {type(value)}"
            ) from e

    def __setattr__(self, name: str, value: Any) -> None:
        """Validate the assigned value, then store it."""
        if name.startswith("_"):
            super().__setattr__(name, value)
            return
        super().__setattr__(name, self._check_value(name, value))

    def update(self, data: dict[str, MetaData]) -> None:
        """Update the settings."""
        validated = {k: self._check_value(k, v) for k, v in data.items()}
        for key, value in validated.items():
            super().__setattr__(key, value)

    def __setitem__(self, key: str, value: MetaData) -> None:
        """Set the value of a setting."""
        setattr(self, key, value)

    def __iadd__(self, other: Info) -> Self:
        """Update the settings."""
        for key, value in other.model_dump().items():
            setattr(self, key, value)
        return self

    def __add__(self, other: Info) -> Self:
        """Update the settings."""
        return self.model_copy(update=other.model_dump())

__add__

__add__(other: Info) -> Self

Update the settings.

Source code in kfactory/settings.py
131
132
133
def __add__(self, other: Info) -> Self:
    """Update the settings."""
    return self.model_copy(update=other.model_dump())

__iadd__

__iadd__(other: Info) -> Self

Update the settings.

Source code in kfactory/settings.py
125
126
127
128
129
def __iadd__(self, other: Info) -> Self:
    """Update the settings."""
    for key, value in other.model_dump().items():
        setattr(self, key, value)
    return self

__init__

__init__(**kwargs: Any) -> None

Initialize the settings.

Source code in kfactory/settings.py
85
86
87
def __init__(self, **kwargs: Any) -> None:
    """Initialize the settings."""
    super().__init__(**kwargs)

__setattr__

__setattr__(name: str, value: Any) -> None

Validate the assigned value, then store it.

Source code in kfactory/settings.py
108
109
110
111
112
113
def __setattr__(self, name: str, value: Any) -> None:
    """Validate the assigned value, then store it."""
    if name.startswith("_"):
        super().__setattr__(name, value)
        return
    super().__setattr__(name, self._check_value(name, value))

__setitem__

__setitem__(key: str, value: MetaData) -> None

Set the value of a setting.

Source code in kfactory/settings.py
121
122
123
def __setitem__(self, key: str, value: MetaData) -> None:
    """Set the value of a setting."""
    setattr(self, key, value)

restrict_types pydantic-validator

restrict_types(
    data: dict[str, MetaData],
) -> dict[str, MetaData]

Restrict the types of the settings (runs at construction only).

Source code in kfactory/settings.py
89
90
91
92
93
94
95
@model_validator(mode="before")
@classmethod
def restrict_types(cls, data: dict[str, MetaData]) -> dict[str, MetaData]:
    """Restrict the types of the settings (runs at construction only)."""
    for name, value in data.items():
        data[name] = cls._check_value(name, value)
    return data

update

update(data: dict[str, MetaData]) -> None

Update the settings.

Source code in kfactory/settings.py
115
116
117
118
119
def update(self, data: dict[str, MetaData]) -> None:
    """Update the settings."""
    validated = {k: self._check_value(k, v) for k, v in data.items()}
    for key, value in validated.items():
        super().__setattr__(key, value)

KCellSettings pydantic-model

Bases: SettingMixin, BaseModel

Settings for a BaseKCell.

Validators:

Source code in kfactory/settings.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class KCellSettings(
    SettingMixin, BaseModel, extra="allow", validate_assignment=True, frozen=True
):
    """Settings for a BaseKCell."""

    def __init__(self, **kwargs: Any) -> None:
        """Initialize the settings."""
        super().__init__(**kwargs)

    @model_validator(mode="before")
    @classmethod
    def restrict_types(cls, data: dict[str, Any]) -> dict[str, MetaData]:
        """Restrict the types of the settings."""
        for name, value in data.items():
            data[name] = convert_metadata_type(value)
        return data

__init__

__init__(**kwargs: Any) -> None

Initialize the settings.

Source code in kfactory/settings.py
44
45
46
def __init__(self, **kwargs: Any) -> None:
    """Initialize the settings."""
    super().__init__(**kwargs)

restrict_types pydantic-validator

restrict_types(data: dict[str, Any]) -> dict[str, MetaData]

Restrict the types of the settings.

Source code in kfactory/settings.py
48
49
50
51
52
53
54
@model_validator(mode="before")
@classmethod
def restrict_types(cls, data: dict[str, Any]) -> dict[str, MetaData]:
    """Restrict the types of the settings."""
    for name, value in data.items():
        data[name] = convert_metadata_type(value)
    return data

KCellSettingsUnits pydantic-model

Bases: SettingMixin, BaseModel

Settings for the units of a KCell.

Validators:

Source code in kfactory/settings.py
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
class KCellSettingsUnits(
    SettingMixin, BaseModel, extra="allow", validate_assignment=True, frozen=True
):
    """Settings for the units of a KCell."""

    def __init__(self, **kwargs: Any) -> None:
        """Initialize the settings."""
        super().__init__(**kwargs)

    @model_validator(mode="before")
    @classmethod
    def restrict_types(cls, data: dict[str, str]) -> dict[str, str]:
        """Restrict the types of the settings."""
        for name, value in data.items():
            data[name] = str(value)
        return data

__init__

__init__(**kwargs: Any) -> None

Initialize the settings.

Source code in kfactory/settings.py
62
63
64
def __init__(self, **kwargs: Any) -> None:
    """Initialize the settings."""
    super().__init__(**kwargs)

restrict_types pydantic-validator

restrict_types(data: dict[str, str]) -> dict[str, str]

Restrict the types of the settings.

Source code in kfactory/settings.py
66
67
68
69
70
71
72
@model_validator(mode="before")
@classmethod
def restrict_types(cls, data: dict[str, str]) -> dict[str, str]:
    """Restrict the types of the settings."""
    for name, value in data.items():
        data[name] = str(value)
    return data

SettingMixin

Mixin class for shared settings functionality.

Source code in kfactory/settings.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class SettingMixin:
    """Mixin class for shared settings functionality."""

    def __getattr__(self, key: str) -> Any:
        """Get the value of a setting."""
        return super().__getattr__(key)  # ty:ignore[unresolved-attribute]

    def __getitem__(self, key: str) -> Any:
        """Get the value of a setting."""
        return getattr(self, key)

    def get(self, __key: str, /, default: Any = None) -> Any:
        """Get the value of a setting."""
        return getattr(self, __key, default)

    def __contains__(self, __key: str, /) -> bool:
        """Check if a setting exists."""
        return hasattr(self, __key)

    def __str__(self) -> str:
        """Return the representation of the settings."""
        return repr(self)

__contains__

__contains__(__key: str) -> bool

Check if a setting exists.

Source code in kfactory/settings.py
30
31
32
def __contains__(self, __key: str, /) -> bool:
    """Check if a setting exists."""
    return hasattr(self, __key)

__getattr__

__getattr__(key: str) -> Any

Get the value of a setting.

Source code in kfactory/settings.py
18
19
20
def __getattr__(self, key: str) -> Any:
    """Get the value of a setting."""
    return super().__getattr__(key)  # ty:ignore[unresolved-attribute]

__getitem__

__getitem__(key: str) -> Any

Get the value of a setting.

Source code in kfactory/settings.py
22
23
24
def __getitem__(self, key: str) -> Any:
    """Get the value of a setting."""
    return getattr(self, key)

__str__

__str__() -> str

Return the representation of the settings.

Source code in kfactory/settings.py
34
35
36
def __str__(self) -> str:
    """Return the representation of the settings."""
    return repr(self)

get

get(__key: str, /, default: Any = None) -> Any

Get the value of a setting.

Source code in kfactory/settings.py
26
27
28
def get(self, __key: str, /, default: Any = None) -> Any:
    """Get the value of a setting."""
    return getattr(self, __key, default)