Custom Data Type (custom_data_type.py)¶
Purpose¶
Shows how to create and use a custom BaseDataType implementation.
- Normalize and persist a value in a consistent representation
- Demonstrate the required
convertmethod - (Optionally) override
__str__for serialization formatting
Implementation¶
from configparser import ConfigParser
from pathlib import Path
from confkit import Config
from confkit.data_types import BaseDataType
# Configure parser + file
parser = ConfigParser()
Config.set_parser(parser)
Config.set_file(Path("config.ini"))
class UpperString(BaseDataType[str]):
"""String that is always stored / returned in UPPER CASE."""
def convert(self, value: str) -> str: # raw INI -> normalized
return str(value).upper()
def __str__(self, value: str): # normalized -> persisted string
return value.upper()
class CustomCfg:
shout_name = Config(UpperString("confkit"))
print(CustomCfg.shout_name) # CONFKIT
CustomCfg.shout_name = "MixedCase"
print(CustomCfg.shout_name) # MIXEDCASE
Generated File Snippet¶
After the first run (values normalized):
[CustomCfg]
shout_name = CONFKIT
After reassignment:
[CustomCfg]
shout_name = MIXEDCASE
Design Notes¶
convertshould raise an appropriate exception (letBaseDataType.validatehelp if you call it) when input cannot be parsed.- Override
validateif you need domain rules (e.g. length limits). Callsuper().validate()if stacking behavior. __str__mainly matters when you want the persisted form to differ fromstr(value).
Integration Checklist¶
- Create subclass
class X(BaseDataType[T]): - Implement
convert(self, value: str) -> T - (Optional) override
__str__(self, value: T) -> str - (Optional) override
validate(self, value: T)for domain constraints. - Use with
Config(X(default_value))
Related Docs¶
- Usage Guide: Adding a New Data Type
- Reference: Data Types
- Source example:
examples/custom_data_type.py