-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustom_data_type.py
More file actions
73 lines (56 loc) · 2.25 KB
/
custom_data_type.py
File metadata and controls
73 lines (56 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
"""Custom data type example for confkit.
Demonstrates how to:
1. Subclass BaseDataType[T]
2. Implement convert()
3. (Optionally) override __str__ for serialization
4. Use with Config descriptor
Run with:
uv run python examples/custom_data_type.py
This example creates a `UpperString` type that always stores values upper-cased
in the config file, while presenting them upper-cased when read.
"""
from __future__ import annotations
from configparser import ConfigParser
from pathlib import Path
from confkit import Config
from confkit.data_types import BaseDataType
Config.set_file(Path("config.ini"))
class UpperString(BaseDataType[str]):
"""Custom string data type that normalizes to UPPER CASE.
Stored *exactly* as upper case in the INI file. Accepts any input that can
be coerced to str.
"""
def __str__(self) -> str:
# Called when storing data in the INI;
return self.value.upper()
def convert(self, value: str) -> str:
"""Convert input to upper case string."""
# Called when reading from INI
return value.upper()
def validate(self) -> bool:
# enforce that value is upper case
# Important! Must call super() first to ensure type conversion
# You may raise an error to provide more information
# Simply returning False will raise a generic error
super().validate()
if self.value.upper() != self.value:
raise ValueError("Value must be upper case")
return True
class CustomConfig:
# Use the custom datatype by instantiating it with a default.
shout_name = Config(UpperString("confkit"))
project = Config(UpperString("Example Project"))
if __name__ == "__main__":
config = CustomConfig()
print("Initial values:")
print("shout_name:", config.shout_name)
print("project:", config.project)
# Assign lower / mixed case; storage normalizes to upper automatically
config.shout_name = "custom"
config.project = "demo Title"
print("\nAfter reassignment:")
print("shout_name:", config.shout_name)
print("project:", config.project)
# Show underlying INI content (optional diagnostic)
ini_text = Path("config.ini").read_text(encoding="utf-8")
print("\nRaw config.ini contents:\n" + ini_text)