confkit

Module that provides the main interface for the confkit package.

It includes the Config class and various data types used for configuration values.

 1"""Module that provides the main interface for the confkit package.
 2
 3It includes the Config class and various data types used for configuration values.
 4"""
 5
 6from .config import Config
 7from .data_types import (
 8    BaseDataType,
 9    Binary,
10    Boolean,
11    Enum,
12    Float,
13    Hex,
14    Integer,
15    IntEnum,
16    IntFlag,
17    List,
18    NoneType,
19    Octal,
20    Optional,
21    StrEnum,
22    String,
23)
24from .exceptions import InvalidConverterError, InvalidDefaultError
25
26__all__ = [
27    "BaseDataType",
28    "Binary",
29    "Boolean",
30    "Config",
31    "Enum",
32    "Float",
33    "Hex",
34    "IntEnum",
35    "IntFlag",
36    "Integer",
37    "InvalidConverterError",
38    "InvalidDefaultError",
39    "List",
40    "NoneType",
41    "Octal",
42    "Optional",
43    "StrEnum",
44    "String",
45]
class BaseDataType(abc.ABC, typing.Generic[~T]):
19class BaseDataType(ABC, Generic[T]):
20    """Base class used for Config descriptors to define a data type."""
21
22    def __init__(self, default: T) -> None:
23        """Initialize the base data type."""
24        self.default = default
25        self.value = default
26        self.type = type(default)
27
28    def __str__(self) -> str:
29        """Return the string representation of the stored value."""
30        return str(self.value)
31
32    @abstractmethod
33    def convert(self, value: str) -> T:
34        """Convert a string value to the desired type."""
35
36    def validate(self) -> bool:
37        """Validate that the value matches the expected type."""
38        orig_bases: tuple[type, ...] | None = getattr(self.__class__, "__orig_bases__", None)
39
40        if not orig_bases:
41            msg = "No type information available for validation."
42            raise InvalidConverterError(msg)
43
44        # Extract type arguments from the generic base
45        for base in orig_bases:
46            if hasattr(base, "__args__"):
47                type_args = base.__args__
48                if type_args:
49                    for type_arg in type_args:
50                        if hasattr(type_arg, "__origin__"):
51                            # For parameterized generics, check against the origin type
52                            if isinstance(self.value, type_arg.__origin__):
53                                return True
54                        elif isinstance(self.value, (self.type, type_arg)):
55                            return True
56                    msg = f"Value {self.value} is not any of {type_args}."
57                    raise InvalidConverterError(msg)
58        msg = "This should not have raised. Report to the library maintainers with code: `DTBDT`"
59        raise TypeError(msg)
60
61    @staticmethod
62    def cast_optional(default: T | None | BaseDataType[T]) -> BaseDataType[T | None]:
63        """Convert the default value to an Optional data type."""
64        if default is None:
65            return cast("BaseDataType[T | None]", NoneType())
66        return Optional(BaseDataType.cast(default))
67
68    @staticmethod
69    def cast(default: T | BaseDataType[T]) -> BaseDataType[T]:
70        """Convert the default value to a BaseDataType."""
71        # We use Cast to shut up type checkers, as we know primitive types will be correct.
72        # If a custom type is passed, it should be a BaseDataType subclass, which already has the correct types.
73        match default:
74            case bool():
75                data_type = cast("BaseDataType[T]", Boolean(default))
76            case None:
77                data_type = cast("BaseDataType[T]", NoneType())
78            case int():
79                data_type = cast("BaseDataType[T]", Integer(default))
80            case float():
81                data_type = cast("BaseDataType[T]", Float(default))
82            case str():
83                data_type = cast("BaseDataType[T]", String(default))
84            case BaseDataType():
85                data_type = default
86            case _:
87                msg = (
88                    f"Unsupported default value type: {type(default).__name__}. "
89                    "Use a BaseDataType subclass for custom types."
90                )
91                raise InvalidDefaultError(msg)
92        return data_type

Base class used for Config descriptors to define a data type.

BaseDataType(default: ~T)
22    def __init__(self, default: T) -> None:
23        """Initialize the base data type."""
24        self.default = default
25        self.value = default
26        self.type = type(default)

Initialize the base data type.

default
value
type
@abstractmethod
def convert(self, value: str) -> ~T:
32    @abstractmethod
33    def convert(self, value: str) -> T:
34        """Convert a string value to the desired type."""

Convert a string value to the desired type.

def validate(self) -> bool:
36    def validate(self) -> bool:
37        """Validate that the value matches the expected type."""
38        orig_bases: tuple[type, ...] | None = getattr(self.__class__, "__orig_bases__", None)
39
40        if not orig_bases:
41            msg = "No type information available for validation."
42            raise InvalidConverterError(msg)
43
44        # Extract type arguments from the generic base
45        for base in orig_bases:
46            if hasattr(base, "__args__"):
47                type_args = base.__args__
48                if type_args:
49                    for type_arg in type_args:
50                        if hasattr(type_arg, "__origin__"):
51                            # For parameterized generics, check against the origin type
52                            if isinstance(self.value, type_arg.__origin__):
53                                return True
54                        elif isinstance(self.value, (self.type, type_arg)):
55                            return True
56                    msg = f"Value {self.value} is not any of {type_args}."
57                    raise InvalidConverterError(msg)
58        msg = "This should not have raised. Report to the library maintainers with code: `DTBDT`"
59        raise TypeError(msg)

Validate that the value matches the expected type.

@staticmethod
def cast_optional( default: Union[~T, NoneType, BaseDataType[~T]]) -> BaseDataType[typing.Optional[~T]]:
61    @staticmethod
62    def cast_optional(default: T | None | BaseDataType[T]) -> BaseDataType[T | None]:
63        """Convert the default value to an Optional data type."""
64        if default is None:
65            return cast("BaseDataType[T | None]", NoneType())
66        return Optional(BaseDataType.cast(default))

Convert the default value to an Optional data type.

@staticmethod
def cast( default: Union[~T, BaseDataType[~T]]) -> BaseDataType[~T]:
68    @staticmethod
69    def cast(default: T | BaseDataType[T]) -> BaseDataType[T]:
70        """Convert the default value to a BaseDataType."""
71        # We use Cast to shut up type checkers, as we know primitive types will be correct.
72        # If a custom type is passed, it should be a BaseDataType subclass, which already has the correct types.
73        match default:
74            case bool():
75                data_type = cast("BaseDataType[T]", Boolean(default))
76            case None:
77                data_type = cast("BaseDataType[T]", NoneType())
78            case int():
79                data_type = cast("BaseDataType[T]", Integer(default))
80            case float():
81                data_type = cast("BaseDataType[T]", Float(default))
82            case str():
83                data_type = cast("BaseDataType[T]", String(default))
84            case BaseDataType():
85                data_type = default
86            case _:
87                msg = (
88                    f"Unsupported default value type: {type(default).__name__}. "
89                    "Use a BaseDataType subclass for custom types."
90                )
91                raise InvalidDefaultError(msg)
92        return data_type

Convert the default value to a BaseDataType.

class Binary(confkit.BaseDataType[bytes | int]):
320class Binary(BaseDataType[bytes | int]):
321    """A config value that represents binary."""
322
323    def __init__(self, default: bytes | int = 0) -> None:  # noqa: D107
324        if isinstance(default, bytes):
325            default = int.from_bytes(default)
326        super().__init__(default)
327
328    def __str__(self) -> str:  # noqa: D105
329        if isinstance(self.value, bytes):
330            self.value = int.from_bytes(self.value)
331        return f"0b{self.value:b}"
332
333    def convert(self, value: str) -> int:
334        """Convert a string value to an integer from binary."""
335        return int(value.removeprefix("0b"), 2)

A config value that represents binary.

Binary(default: bytes | int = 0)
323    def __init__(self, default: bytes | int = 0) -> None:  # noqa: D107
324        if isinstance(default, bytes):
325            default = int.from_bytes(default)
326        super().__init__(default)

Initialize the base data type.

def convert(self, value: str) -> int:
333    def convert(self, value: str) -> int:
334        """Convert a string value to an integer from binary."""
335        return int(value.removeprefix("0b"), 2)

Convert a string value to an integer from binary.

class Boolean(confkit.BaseDataType[bool]):
236class Boolean(BaseDataType[bool]):
237    """A config value that is a boolean."""
238
239    def __init__(self, default: bool = False) -> None:  # noqa: D107, FBT001, FBT002
240        super().__init__(default)
241
242    def convert(self, value: str) -> bool:
243        """Convert a string value to a boolean."""
244        if value.lower() in {"true", "1", "yes"}:
245            return True
246        if value.lower() in {"false", "0", "no"}:
247            return False
248        msg = f"Cannot convert {value} to boolean."
249        raise ValueError(msg)

A config value that is a boolean.

Boolean(default: bool = False)
239    def __init__(self, default: bool = False) -> None:  # noqa: D107, FBT001, FBT002
240        super().__init__(default)

Initialize the base data type.

def convert(self, value: str) -> bool:
242    def convert(self, value: str) -> bool:
243        """Convert a string value to a boolean."""
244        if value.lower() in {"true", "1", "yes"}:
245            return True
246        if value.lower() in {"false", "0", "no"}:
247            return False
248        msg = f"Cannot convert {value} to boolean."
249        raise ValueError(msg)

Convert a string value to a boolean.

class Config(typing.Generic[~VT]):
 30class Config(Generic[VT]):
 31    """A descriptor for config values, preserving type information.
 32
 33    the ValueType (VT) is the type you want the config value to be.
 34    """
 35
 36    validate_types: ClassVar[bool] = True # Validate that the converter returns the same type as the default value. (not strict)
 37    write_on_edit: ClassVar[bool] = True # Write to the config file when updating a value.
 38    optional: bool = False # if True, allows None as an extra type when validating types. (both instance and class variables.)
 39
 40    _parser: ConfigParser = UNSET
 41    _file: Path = UNSET
 42    _has_read_config: bool = False
 43
 44    if TYPE_CHECKING:
 45        # Overloads for type checkers to understand the different settings of the Config descriptors.
 46        @overload
 47        def __init__(self: Config[str], default: str) -> None: ...
 48        @overload
 49        def __init__(self: Config[None], default: None) -> None: ...
 50        @overload
 51        def __init__(self: Config[bool], default: bool) -> None: ...  # noqa: FBT001
 52        @overload
 53        def __init__(self: Config[int], default: int) -> None: ...
 54        @overload
 55        def __init__(self: Config[float], default: float) -> None: ...
 56        @overload
 57        def __init__(self: Config[str | None], default: str, *, optional: bool) -> None: ...
 58        @overload
 59        def __init__(self: Config[None], default: None, *, optional: bool) -> None: ...
 60        @overload
 61        def __init__(self: Config[bool | None], default: bool, *, optional: bool) -> None: ...  # noqa: FBT001
 62        @overload
 63        def __init__(self: Config[int | None], default: int, *, optional: bool) -> None: ...
 64        @overload
 65        def __init__(self: Config[float | None], default: float, *, optional: bool) -> None: ...
 66        @overload # Custom data type, like Enum's or custom class.
 67        def __init__(self, default: BaseDataType[VT]) -> None: ...
 68
 69    # type Complains about the self and default overloads for None and str
 70    # they are explicitly set for type checkers, the actual representation doesn't matter
 71    # in runtime, as VT is allowed to be any type.
 72    def __init__( # type: ignore[reportInconsistentOverload]
 73        self,
 74        default: VT | None | BaseDataType[VT] = UNSET,
 75        *,
 76        optional: bool = False,
 77    ) -> None:
 78        """Initialize the config descriptor with a default value.
 79
 80        Validate that parser and filepath are present.
 81        """
 82        cls = self.__class__
 83        self.optional = optional or cls.optional # Be truthy when either one is true.
 84
 85        if not self.optional and default is UNSET:
 86            msg = "Default value cannot be None when optional is False."
 87            raise InvalidDefaultError(msg)
 88
 89        self._initialize_data_type(default)
 90        self._validate_init()
 91        self._read_parser()
 92
 93    def __init_subclass__(cls) -> None:
 94        """Allow for multiple config files/parsers without conflicts."""
 95        super().__init_subclass__()
 96
 97        parent = cls._find_parent()
 98
 99        cls.validate_types = parent.validate_types
100        cls.write_on_edit = parent.write_on_edit
101        cls._parser = parent._parser  # noqa: SLF001
102        cls._file = parent._file  # noqa: SLF001
103        cls._has_read_config = parent._has_read_config  # noqa: SLF001
104
105    @classmethod
106    def _find_parent(cls) -> type[Config[Any]]:
107        for base in cls.__bases__:
108            if issubclass(base, Config):
109                parent = base
110                break
111        else:
112            parent = Config
113        return parent
114
115    def _initialize_data_type(self, default: VT | None | BaseDataType[VT]) -> None:
116        """Initialize the data type based on the default value."""
117        if not self.optional and default is not None:
118            self._data_type = BaseDataType[VT].cast(default)
119        else:
120            self._data_type = BaseDataType[VT].cast_optional(default)
121
122    def _read_parser(self) -> None:
123        """Ensure the parser has read the file at initialization. Avoids rewriting the file when settings are already set."""
124        if not self._has_read_config:
125            self._parser.read(self._file)
126            self._has_read_config = True
127
128    def _validate_init(self) -> None:
129        """Validate the config descriptor, ensuring it's properly set up."""
130        self.validate_file()
131        self.validate_parser()
132
133    def convert(self, value: str) -> VT:
134        """Convert the value to the desired type using the given converter method."""
135        # Ignore the type error of VT, type checkers don't like None as an option
136        # We handle it using the `optional` flag, or using Optional DataType. so we can safely ignore it.
137        return self._data_type.convert(value) # type: ignore[reportReturnType]
138
139    @classmethod
140    def set_parser(cls, parser: ConfigParser) -> None:
141        """Set the parser for ALL descriptors."""
142        if cls is Config:
143            # Warn users that setting this value on the base class can lead to unexpected behavoir.
144            # Tell the user to subclass <Config> first.
145            warnings.warn("<Config> is the base class. Subclass <Config> to avoid unexpected behavior.", stacklevel=2)
146        cls._parser = parser
147
148    @classmethod
149    def set_file(cls, file: Path) -> None:
150        """Set the file for ALL descriptors."""
151        if cls is Config:
152            # Warn users that setting this value on the base class can lead to unexpected behavoir.
153            # Tell the user to subclass <Config> first.
154            warnings.warn("<Config> is the base class. Subclass <Config> to avoid unexpected behavior.", stacklevel=2)
155        cls._file = file
156
157    def validate_strict_type(self) -> None:
158        """Validate the type of the converter matches the desired type."""
159        if self._data_type.convert is UNSET:
160            msg = "Converter is not set."
161            raise InvalidConverterError(msg)
162
163        cls = self.__class__
164        self.__config_value = cls._parser.get(self._section, self._setting)
165        self.__converted_value = self.convert(self.__config_value)
166
167        if not cls.validate_types:
168            return
169        if not self._data_type.validate():
170            msg = f"Invalid value for {self._section}.{self._setting}: {self.__converted_value}"
171            raise InvalidConverterError(msg)
172
173        self.__converted_type = type(self.__converted_value)
174        default_value_type = type(self._data_type.default)
175
176        is_optional = self.optional or isinstance(self._data_type, Optional)
177        if (is_optional) and self.__converted_type in (default_value_type, NoneType):
178            # Allow None or the same type as the default value to be returned by the converter when _optional is True.
179            return
180        if self.__converted_type is not default_value_type:
181            msg = f"Converter does not return the same type as the default value <{default_value_type}> got <{self.__converted_type}>."  # noqa: E501
182            raise InvalidConverterError(msg)
183
184    @classmethod
185    def validate_file(cls) -> None:
186        """Validate the config file."""
187        if cls._file is UNSET:
188            msg = f"Config file is not set. use {cls.__name__}.set_file() to set it."
189            raise ValueError(msg)
190
191    @classmethod
192    def validate_parser(cls) -> None:
193        """Validate the config parser."""
194        if cls._parser is UNSET:
195            msg = f"Config parser is not set. use {cls.__name__}.set_parser() to set it."
196            raise ValueError(msg)
197
198    def __set_name__(self, owner: type, name: str) -> None:
199        """Set the name of the attribute to the name of the descriptor."""
200        self.name = name
201        self._section = owner.__name__
202        self._setting = name
203        self._ensure_option()
204        cls = self.__class__
205        self._original_value = cls._parser.get(self._section, self._setting) or self._data_type.default
206        self.private = f"_{self._section}_{self._setting}_{self.name}"
207
208    def _ensure_section(self) -> None:
209        """Ensure the section exists in the config file. Creates one if it doesn't exist."""
210        if not self._parser.has_section(self._section):
211            self._parser.add_section(self._section)
212
213    def _ensure_option(self) -> None:
214        """Ensure the option exists in the config file. Creates one if it doesn't exist."""
215        self._ensure_section()
216        if not self._parser.has_option(self._section, self._setting):
217            cls = self.__class__
218            cls._set(self._section, self._setting, self._data_type)
219
220    def __get__(self, obj: object, obj_type: object) -> VT:
221        """Get the value of the attribute."""
222        # obj_type is the class in which the variable is defined
223        # so it can be different than type of VT
224        # but we don't need obj or it's type to get the value from config in our case.
225        self.validate_strict_type()
226        return self.__converted_value
227
228    def __set__(self, obj: object, value: VT) -> None:
229        """Set the value of the attribute."""
230        self._data_type.value = value
231        cls = self.__class__
232        cls._set(self._section, self._setting, self._data_type)
233        setattr(obj, self.private, value)
234
235    @staticmethod
236    def _sanitize_str(value: str) -> str:
237        """Escape the percent sign in the value."""
238        return value.replace("%", "%%")
239
240    @classmethod
241    def _set(cls, section: str, setting: str, value: VT | BaseDataType[VT] | BaseDataType[VT | None]) -> None:
242        """Set a config value, and write it to the file."""
243        if not cls._parser.has_section(section):
244            cls._parser.add_section(section)
245
246        sanitized_str = cls._sanitize_str(str(value))
247        cls._parser.set(section, setting, sanitized_str)
248
249        if cls.write_on_edit:
250            cls.write()
251
252
253    @classmethod
254    def write(cls) -> None:
255        """Write the config parser to the file."""
256        cls.validate_file()
257        with cls._file.open("w") as f:
258            cls._parser.write(f)
259
260    @classmethod
261    def set(cls, section: str, setting: str, value: VT):  # noqa: ANN206
262        """Set a config value using this descriptor."""
263
264        def wrapper(func: Callable[..., F]) -> Callable[..., F]:
265            @wraps(func)
266            def inner(*args: P.args, **kwargs: P.kwargs) -> F:
267                cls._set(section, setting, value)
268                return func(*args, **kwargs)
269
270            return inner
271        return wrapper
272
273
274    @classmethod
275    def with_setting(cls, setting: Config[OVT]):  # noqa: ANN206
276        """Insert a config value into **kwargs to the wrapped method/function using this decorator."""
277        def wrapper(func: Callable[..., F]) -> Callable[..., F]:
278            @wraps(func)
279            def inner(*args: P.args, **kwargs: P.kwargs) -> F:
280                kwargs[setting.name] = setting.convert(cls._parser.get(setting._section, setting._setting))
281                return func(*args, **kwargs)
282
283            return inner
284        return wrapper
285
286
287    @classmethod
288    def with_kwarg(cls, section: str, setting: str, name: str | None = None, default: VT = UNSET):  # noqa: ANN206
289        """Insert a config value into **kwargs to the wrapped method/function using this descriptor.
290
291        Use kwarg.get(`name`) to get the value.
292        `name` is the name the kwarg gets if passed, if None, it will be the same as `setting`.
293        Section parameter is just for finding the config value.
294        """
295        if name is None:
296            name = setting
297        if default is UNSET and not cls._parser.has_option(section, setting):
298            msg = f"Config value {section=} {setting=} is not set. and no default value is given."
299            raise ValueError(msg)
300
301        def wrapper(func: Callable[..., F]) -> Callable[..., F]:
302            @wraps(func)
303            def inner(*args: P.args, **kwargs: P.kwargs) -> F:
304                if default is not UNSET:
305                    cls._set_default(section, setting, default)
306                kwargs[name] = cls._parser.get(section, setting) # ty: ignore[invalid-assignment]
307                return func(*args, **kwargs)
308
309            return inner
310        return wrapper
311
312    @classmethod
313    def _set_default(cls, section: str, setting: str, value: VT) -> None:
314        if cls._parser.get(section, setting, fallback=UNSET) is UNSET:
315            cls._set(section, setting, value)
316
317    @classmethod
318    def default(cls, section: str, setting: str, value: VT):  # noqa: ANN206
319        """Set a default config value if none are set yet using this descriptor."""
320        def wrapper(func: Callable[..., F]) -> Callable[..., F]:
321            @wraps(func)
322            def inner(*args: P.args, **kwargs: P.kwargs) -> F:
323                cls._set_default(section, setting, value)
324                return func(*args, **kwargs)
325
326            return inner
327        return wrapper

A descriptor for config values, preserving type information.

the ValueType (VT) is the type you want the config value to be.

Config( default: Union[~VT, NoneType, BaseDataType[~VT]] = MISSING, *, optional: bool = False)
72    def __init__( # type: ignore[reportInconsistentOverload]
73        self,
74        default: VT | None | BaseDataType[VT] = UNSET,
75        *,
76        optional: bool = False,
77    ) -> None:
78        """Initialize the config descriptor with a default value.
79
80        Validate that parser and filepath are present.
81        """
82        cls = self.__class__
83        self.optional = optional or cls.optional # Be truthy when either one is true.
84
85        if not self.optional and default is UNSET:
86            msg = "Default value cannot be None when optional is False."
87            raise InvalidDefaultError(msg)
88
89        self._initialize_data_type(default)
90        self._validate_init()
91        self._read_parser()

Initialize the config descriptor with a default value.

Validate that parser and filepath are present.

validate_types: ClassVar[bool] = True
write_on_edit: ClassVar[bool] = True
optional: bool = False
def convert(self, value: str) -> ~VT:
133    def convert(self, value: str) -> VT:
134        """Convert the value to the desired type using the given converter method."""
135        # Ignore the type error of VT, type checkers don't like None as an option
136        # We handle it using the `optional` flag, or using Optional DataType. so we can safely ignore it.
137        return self._data_type.convert(value) # type: ignore[reportReturnType]

Convert the value to the desired type using the given converter method.

@classmethod
def set_parser(cls, parser: configparser.ConfigParser) -> None:
139    @classmethod
140    def set_parser(cls, parser: ConfigParser) -> None:
141        """Set the parser for ALL descriptors."""
142        if cls is Config:
143            # Warn users that setting this value on the base class can lead to unexpected behavoir.
144            # Tell the user to subclass <Config> first.
145            warnings.warn("<Config> is the base class. Subclass <Config> to avoid unexpected behavior.", stacklevel=2)
146        cls._parser = parser

Set the parser for ALL descriptors.

@classmethod
def set_file(cls, file: pathlib.Path) -> None:
148    @classmethod
149    def set_file(cls, file: Path) -> None:
150        """Set the file for ALL descriptors."""
151        if cls is Config:
152            # Warn users that setting this value on the base class can lead to unexpected behavoir.
153            # Tell the user to subclass <Config> first.
154            warnings.warn("<Config> is the base class. Subclass <Config> to avoid unexpected behavior.", stacklevel=2)
155        cls._file = file

Set the file for ALL descriptors.

def validate_strict_type(self) -> None:
157    def validate_strict_type(self) -> None:
158        """Validate the type of the converter matches the desired type."""
159        if self._data_type.convert is UNSET:
160            msg = "Converter is not set."
161            raise InvalidConverterError(msg)
162
163        cls = self.__class__
164        self.__config_value = cls._parser.get(self._section, self._setting)
165        self.__converted_value = self.convert(self.__config_value)
166
167        if not cls.validate_types:
168            return
169        if not self._data_type.validate():
170            msg = f"Invalid value for {self._section}.{self._setting}: {self.__converted_value}"
171            raise InvalidConverterError(msg)
172
173        self.__converted_type = type(self.__converted_value)
174        default_value_type = type(self._data_type.default)
175
176        is_optional = self.optional or isinstance(self._data_type, Optional)
177        if (is_optional) and self.__converted_type in (default_value_type, NoneType):
178            # Allow None or the same type as the default value to be returned by the converter when _optional is True.
179            return
180        if self.__converted_type is not default_value_type:
181            msg = f"Converter does not return the same type as the default value <{default_value_type}> got <{self.__converted_type}>."  # noqa: E501
182            raise InvalidConverterError(msg)

Validate the type of the converter matches the desired type.

@classmethod
def validate_file(cls) -> None:
184    @classmethod
185    def validate_file(cls) -> None:
186        """Validate the config file."""
187        if cls._file is UNSET:
188            msg = f"Config file is not set. use {cls.__name__}.set_file() to set it."
189            raise ValueError(msg)

Validate the config file.

@classmethod
def validate_parser(cls) -> None:
191    @classmethod
192    def validate_parser(cls) -> None:
193        """Validate the config parser."""
194        if cls._parser is UNSET:
195            msg = f"Config parser is not set. use {cls.__name__}.set_parser() to set it."
196            raise ValueError(msg)

Validate the config parser.

@classmethod
def write(cls) -> None:
253    @classmethod
254    def write(cls) -> None:
255        """Write the config parser to the file."""
256        cls.validate_file()
257        with cls._file.open("w") as f:
258            cls._parser.write(f)

Write the config parser to the file.

@classmethod
def set(cls, section: str, setting: str, value: ~VT):
260    @classmethod
261    def set(cls, section: str, setting: str, value: VT):  # noqa: ANN206
262        """Set a config value using this descriptor."""
263
264        def wrapper(func: Callable[..., F]) -> Callable[..., F]:
265            @wraps(func)
266            def inner(*args: P.args, **kwargs: P.kwargs) -> F:
267                cls._set(section, setting, value)
268                return func(*args, **kwargs)
269
270            return inner
271        return wrapper

Set a config value using this descriptor.

@classmethod
def with_setting(cls, setting: Config[~OVT]):
274    @classmethod
275    def with_setting(cls, setting: Config[OVT]):  # noqa: ANN206
276        """Insert a config value into **kwargs to the wrapped method/function using this decorator."""
277        def wrapper(func: Callable[..., F]) -> Callable[..., F]:
278            @wraps(func)
279            def inner(*args: P.args, **kwargs: P.kwargs) -> F:
280                kwargs[setting.name] = setting.convert(cls._parser.get(setting._section, setting._setting))
281                return func(*args, **kwargs)
282
283            return inner
284        return wrapper

Insert a config value into **kwargs to the wrapped method/function using this decorator.

@classmethod
def with_kwarg( cls, section: str, setting: str, name: str | None = None, default: ~VT = MISSING):
287    @classmethod
288    def with_kwarg(cls, section: str, setting: str, name: str | None = None, default: VT = UNSET):  # noqa: ANN206
289        """Insert a config value into **kwargs to the wrapped method/function using this descriptor.
290
291        Use kwarg.get(`name`) to get the value.
292        `name` is the name the kwarg gets if passed, if None, it will be the same as `setting`.
293        Section parameter is just for finding the config value.
294        """
295        if name is None:
296            name = setting
297        if default is UNSET and not cls._parser.has_option(section, setting):
298            msg = f"Config value {section=} {setting=} is not set. and no default value is given."
299            raise ValueError(msg)
300
301        def wrapper(func: Callable[..., F]) -> Callable[..., F]:
302            @wraps(func)
303            def inner(*args: P.args, **kwargs: P.kwargs) -> F:
304                if default is not UNSET:
305                    cls._set_default(section, setting, default)
306                kwargs[name] = cls._parser.get(section, setting) # ty: ignore[invalid-assignment]
307                return func(*args, **kwargs)
308
309            return inner
310        return wrapper

Insert a config value into **kwargs to the wrapped method/function using this descriptor.

Use kwarg.get(name) to get the value. name is the name the kwarg gets if passed, if None, it will be the same as setting. Section parameter is just for finding the config value.

@classmethod
def default(cls, section: str, setting: str, value: ~VT):
317    @classmethod
318    def default(cls, section: str, setting: str, value: VT):  # noqa: ANN206
319        """Set a default config value if none are set yet using this descriptor."""
320        def wrapper(func: Callable[..., F]) -> Callable[..., F]:
321            @wraps(func)
322            def inner(*args: P.args, **kwargs: P.kwargs) -> F:
323                cls._set_default(section, setting, value)
324                return func(*args, **kwargs)
325
326            return inner
327        return wrapper

Set a default config value if none are set yet using this descriptor.

class Enum(confkit.data_types._EnumBase[~EnumType]):
126class Enum(_EnumBase[EnumType]):
127    """A config value that is an enum."""
128
129    def convert(self, value: str) -> EnumType:
130        """Convert a string value to an enum."""
131        value = self._strip_comment(value)
132        parsed_enum_name = value.split(".")[-1]
133        return self.value.__class__[parsed_enum_name]
134
135    def _format_allowed_values(self) -> str:
136        """Format allowed values as comma-separated member names."""
137        enum_class = self.value.__class__
138        return ", ".join(member.name for member in enum_class)
139
140    def _get_value_str(self) -> str:
141        """Get the member name."""
142        return self.value.name

A config value that is an enum.

def convert(self, value: str) -> ~EnumType:
129    def convert(self, value: str) -> EnumType:
130        """Convert a string value to an enum."""
131        value = self._strip_comment(value)
132        parsed_enum_name = value.split(".")[-1]
133        return self.value.__class__[parsed_enum_name]

Convert a string value to an enum.

class Float(confkit.BaseDataType[float]):
225class Float(BaseDataType[float]):
226    """A config value that is a float."""
227
228    def __init__(self, default: float = 0.0) -> None:  # noqa: D107
229        super().__init__(default)
230
231    def convert(self, value: str) -> float:
232        """Convert a string value to a float."""
233        return float(value)

A config value that is a float.

Float(default: float = 0.0)
228    def __init__(self, default: float = 0.0) -> None:  # noqa: D107
229        super().__init__(default)

Initialize the base data type.

def convert(self, value: str) -> float:
231    def convert(self, value: str) -> float:
232        """Convert a string value to a float."""
233        return float(value)

Convert a string value to a float.

class Hex(confkit.BaseDataType[int]):
294class Hex(Integer):
295    """A config value that represents hexadecimal."""
296
297    def __init__(self, default: int = 0, base: int = HEXADECIMAL) -> None:  # noqa: D107
298        super().__init__(default, base)
299
300    def __str__(self) -> str:  # noqa: D105
301        return f"0x{self.value:x}"
302
303    def convert(self, value: str) -> int:
304        """Convert a string value to an integer. from hexadecimal."""
305        return int(value.removeprefix("0x"), 16)

A config value that represents hexadecimal.

Hex(default: int = 0, base: int = 16)
297    def __init__(self, default: int = 0, base: int = HEXADECIMAL) -> None:  # noqa: D107
298        super().__init__(default, base)

Initialize the base data type.

def convert(self, value: str) -> int:
303    def convert(self, value: str) -> int:
304        """Convert a string value to an integer. from hexadecimal."""
305        return int(value.removeprefix("0x"), 16)

Convert a string value to an integer. from hexadecimal.

class IntEnum(confkit.data_types._EnumBase[~IntEnumType]):
163class IntEnum(_EnumBase[IntEnumType]):
164    """A config value that is an enum."""
165
166    def convert(self, value: str) -> IntEnumType:
167        """Convert a string value to an enum."""
168        value = self._strip_comment(value)
169        return self.value.__class__(int(value)) # ty: ignore[invalid-return-type] # ty says "Unknown | IntEnum"
170
171    def _format_allowed_values(self) -> str:
172        """Format allowed values as comma-separated name(value) pairs."""
173        enum_class = self.value.__class__
174        return ", ".join(f"{member.name}({member.value})" for member in enum_class)
175
176    def _get_value_str(self) -> str:
177        """Get the member value as string."""
178        return str(self.value.value)

A config value that is an enum.

def convert(self, value: str) -> ~IntEnumType:
166    def convert(self, value: str) -> IntEnumType:
167        """Convert a string value to an enum."""
168        value = self._strip_comment(value)
169        return self.value.__class__(int(value)) # ty: ignore[invalid-return-type] # ty says "Unknown | IntEnum"

Convert a string value to an enum.

class IntFlag(confkit.data_types._EnumBase[~IntFlagType]):
181class IntFlag(_EnumBase[IntFlagType]):
182    """A config value that is an enum."""
183
184    def convert(self, value: str) -> IntFlagType:
185        """Convert a string value to an enum."""
186        value = self._strip_comment(value)
187        return self.value.__class__(int(value)) # ty: ignore[invalid-return-type] # ty says "Unknown | IntFlag"
188
189    def _format_allowed_values(self) -> str:
190        """Format allowed values as comma-separated name(value) pairs."""
191        enum_class = self.value.__class__
192        return ", ".join(f"{member.name}({member.value})" for member in enum_class)
193
194    def _get_value_str(self) -> str:
195        """Get the member value as string."""
196        return str(self.value.value)

A config value that is an enum.

def convert(self, value: str) -> ~IntFlagType:
184    def convert(self, value: str) -> IntFlagType:
185        """Convert a string value to an enum."""
186        value = self._strip_comment(value)
187        return self.value.__class__(int(value)) # ty: ignore[invalid-return-type] # ty says "Unknown | IntFlag"

Convert a string value to an enum.

class Integer(confkit.BaseDataType[int]):
256class Integer(BaseDataType[int]):
257    """A config value that is an integer."""
258
259    # Define constants for common bases
260
261    def __init__(self, default: int = 0, base: int = DECIMAL) -> None:  # noqa: D107
262        super().__init__(default)
263        self.base = base
264
265    @staticmethod
266    def int_to_base(number: int, base: int) -> int:
267        """Convert an integer to a string representation in a given base."""
268        if number == 0:
269            return 0
270        digits = []
271        while number:
272            digits.append(str(number % base))
273            number //= base
274        return int("".join(reversed(digits)))
275
276    def __str__(self) -> str:  # noqa: D105
277        if self.base == DECIMAL:
278            return str(self.value)
279        # Convert the base 10 int to base 5
280        self.value = self.int_to_base(int(self.value), self.base)
281        return f"{self.base}c{self.value}"
282
283    def convert(self, value: str) -> int:
284        """Convert a string value to an integer."""
285        if "c" in value:
286            base_str, val_str = value.split("c")
287            base = int(base_str)
288            if base != self.base:
289                msg = "Base in string does not match base in Integer while converting."
290                raise ValueError(msg)
291            return int(val_str, self.base)
292        return int(value, self.base)

A config value that is an integer.

Integer(default: int = 0, base: int = 10)
261    def __init__(self, default: int = 0, base: int = DECIMAL) -> None:  # noqa: D107
262        super().__init__(default)
263        self.base = base

Initialize the base data type.

base
@staticmethod
def int_to_base(number: int, base: int) -> int:
265    @staticmethod
266    def int_to_base(number: int, base: int) -> int:
267        """Convert an integer to a string representation in a given base."""
268        if number == 0:
269            return 0
270        digits = []
271        while number:
272            digits.append(str(number % base))
273            number //= base
274        return int("".join(reversed(digits)))

Convert an integer to a string representation in a given base.

def convert(self, value: str) -> int:
283    def convert(self, value: str) -> int:
284        """Convert a string value to an integer."""
285        if "c" in value:
286            base_str, val_str = value.split("c")
287            base = int(base_str)
288            if base != self.base:
289                msg = "Base in string does not match base in Integer while converting."
290                raise ValueError(msg)
291            return int(val_str, self.base)
292        return int(value, self.base)

Convert a string value to an integer.

class InvalidConverterError(builtins.ValueError):
8class InvalidConverterError(ValueError):
9    """Raised when the converter is not set or invalid."""

Raised when the converter is not set or invalid.

class InvalidDefaultError(builtins.ValueError):
4class InvalidDefaultError(ValueError):
5    """Raised when the default value is not set or invalid."""

Raised when the default value is not set or invalid.

class List(confkit.data_types._SequenceType[~T], typing.Generic[~T]):
461class List(_SequenceType[T], Generic[T]):
462    """A config value that is a list of values."""
463
464    def convert(self, value: str) -> list[T]:
465        """Convert a string to a list."""
466        return list(super()._convert(value))

A config value that is a list of values.

def convert(self, value: str) -> list[~T]:
464    def convert(self, value: str) -> list[T]:
465        """Convert a string to a list."""
466        return list(super()._convert(value))

Convert a string to a list.

class NoneType(confkit.BaseDataType[NoneType]):
198class NoneType(BaseDataType[None]):
199    """A config value that is None."""
200
201    null_values: ClassVar[set[str]] = {"none", "null", "nil"}
202
203    def __init__(self) -> None:
204        """Initialize the NoneType data type."""
205        super().__init__(None)
206
207    def convert(self, value: str) -> bool: # type: ignore[reportIncompatibleMethodOverride]
208        """Convert a string value to None."""
209        # Ignore type exception as convert should return True/False for NoneType
210        # to determine if we have a valid null value or not.
211        return value.casefold().strip() in NoneType.null_values

A config value that is None.

NoneType()
203    def __init__(self) -> None:
204        """Initialize the NoneType data type."""
205        super().__init__(None)

Initialize the NoneType data type.

null_values: ClassVar[set[str]] = {'none', 'nil', 'null'}
def convert(self, value: str) -> bool:
207    def convert(self, value: str) -> bool: # type: ignore[reportIncompatibleMethodOverride]
208        """Convert a string value to None."""
209        # Ignore type exception as convert should return True/False for NoneType
210        # to determine if we have a valid null value or not.
211        return value.casefold().strip() in NoneType.null_values

Convert a string value to None.

class Octal(confkit.BaseDataType[int]):
307class Octal(Integer):
308    """A config value that represents octal."""
309
310    def __init__(self, default: int = 0, base: int = OCTAL) -> None:  # noqa: D107
311        super().__init__(default, base)
312
313    def __str__(self) -> str:  # noqa: D105
314        return f"0o{self.value:o}"
315
316    def convert(self, value: str) -> int:
317        """Convert a string value to an integer from octal."""
318        return int(value.removeprefix("0o"), 8)

A config value that represents octal.

Octal(default: int = 0, base: int = 8)
310    def __init__(self, default: int = 0, base: int = OCTAL) -> None:  # noqa: D107
311        super().__init__(default, base)

Initialize the base data type.

def convert(self, value: str) -> int:
316    def convert(self, value: str) -> int:
317        """Convert a string value to an integer from octal."""
318        return int(value.removeprefix("0o"), 8)

Convert a string value to an integer from octal.

class Optional(confkit.BaseDataType[typing.Optional[~T]], typing.Generic[~T]):
337class Optional(BaseDataType[T | None], Generic[T]):
338    """A config value that is optional, can be None or a specific type."""
339
340    _none_type = NoneType()
341
342    def __init__(self, data_type: BaseDataType[T]) -> None:
343        """Initialize the optional data type. Wrapping the provided data type."""
344        self._data_type = data_type
345
346    @property
347    def default(self) -> T | None:
348        """Get the default value of the wrapped data type."""
349        return self._data_type.default
350
351    @property
352    def value(self) -> T | None:
353        """Get the current value of the wrapped data type."""
354        return self._data_type.value
355
356    @value.setter
357    def value(self, value: T | None) -> None:
358        """Set the current value of the wrapped data type."""
359        self._data_type.value = value # type: ignore[reportAttributeAccessIssue]
360
361    def convert(self, value: str) -> T | None:
362        """Convert a string value to the optional type."""
363        if self._none_type.convert(value):
364            return None
365        return self._data_type.convert(value)
366
367    def validate(self) -> bool:
368        """Validate that the value is of the wrapped data type or None."""
369        if self._data_type.value is None:
370            return True
371        return self._data_type.validate()
372
373    def __str__(self) -> str:
374        """Return the string representation of the wrapped data type."""
375        return str(self._data_type)

A config value that is optional, can be None or a specific type.

Optional(data_type: BaseDataType[~T])
342    def __init__(self, data_type: BaseDataType[T]) -> None:
343        """Initialize the optional data type. Wrapping the provided data type."""
344        self._data_type = data_type

Initialize the optional data type. Wrapping the provided data type.

default: Optional[~T]
346    @property
347    def default(self) -> T | None:
348        """Get the default value of the wrapped data type."""
349        return self._data_type.default

Get the default value of the wrapped data type.

value: Optional[~T]
351    @property
352    def value(self) -> T | None:
353        """Get the current value of the wrapped data type."""
354        return self._data_type.value

Get the current value of the wrapped data type.

def convert(self, value: str) -> Optional[~T]:
361    def convert(self, value: str) -> T | None:
362        """Convert a string value to the optional type."""
363        if self._none_type.convert(value):
364            return None
365        return self._data_type.convert(value)

Convert a string value to the optional type.

def validate(self) -> bool:
367    def validate(self) -> bool:
368        """Validate that the value is of the wrapped data type or None."""
369        if self._data_type.value is None:
370            return True
371        return self._data_type.validate()

Validate that the value is of the wrapped data type or None.

class StrEnum(confkit.data_types._EnumBase[~StrEnumType]):
145class StrEnum(_EnumBase[StrEnumType]):
146    """A config value that is an enum."""
147
148    def convert(self, value: str) -> StrEnumType:
149        """Convert a string value to an enum."""
150        value = self._strip_comment(value)
151        return self.value.__class__(value) # ty: ignore[invalid-return-type] # this is correct. ty says "Unknown | StrEnum"
152
153    def _format_allowed_values(self) -> str:
154        """Format allowed values as comma-separated member values."""
155        enum_class = self.value.__class__
156        return ", ".join(member.value for member in enum_class)
157
158    def _get_value_str(self) -> str:
159        """Get the member value."""
160        return self.value.value

A config value that is an enum.

def convert(self, value: str) -> ~StrEnumType:
148    def convert(self, value: str) -> StrEnumType:
149        """Convert a string value to an enum."""
150        value = self._strip_comment(value)
151        return self.value.__class__(value) # ty: ignore[invalid-return-type] # this is correct. ty says "Unknown | StrEnum"

Convert a string value to an enum.

class String(confkit.BaseDataType[str]):
214class String(BaseDataType[str]):
215    """A config value that is a string."""
216
217    def __init__(self, default: str = "") -> None:  # noqa: D107
218        super().__init__(default)
219
220    def convert(self, value: str) -> str:
221        """Convert a string value to a string."""
222        return value

A config value that is a string.

String(default: str = '')
217    def __init__(self, default: str = "") -> None:  # noqa: D107
218        super().__init__(default)

Initialize the base data type.

def convert(self, value: str) -> str:
220    def convert(self, value: str) -> str:
221        """Convert a string value to a string."""
222        return value

Convert a string value to a string.