Leaf types¶
Tip
Code for examples on this page can be found in examples/4_leaf_types.
Leaf types are concrete types that can be defined by a single dictionary or collection entry of the configuration. They include scalar types, but they are not limited to them.
Enum¶
You can pass either the key or the value of the desired entry to define an enum argument.
$ uv run enum_value.py --value FOO
Config(value=<Value.FOO: 1>)
$ uv run enum_value.py --value 2
Config(value=<Value.BAR: 2>)
Nitpicker's corner
The argument is first matched against the key, then the value. You don't need to know this unless you are dealing with an enum whose keys and values are inconsistent — let's hope you don't.
Path¶
The Path class is treated as a leaf type in confarg.
A value of type Path is directly constructed from a string.
Decimal and UUID¶
Decimal and UUID are leaf types too, each constructed from its text.
$ uv run decimal_value.py --price 1.10 --id 12345678-1234-5678-1234-567812345678
Config(price=Decimal('1.10'), id=UUID('12345678-1234-5678-1234-567812345678'))
A number in a configuration file is read as it is written, so price: 1.1 is Decimal('1.1'), not the binary expansion of the float the file's parser produced.
Dates, times and durations¶
date, datetime, time, timedelta and timezone are leaf types too, each written as ISO 8601 text.
$ uv run dates.py --day 2021-02-03 --start 2021-02-03T10:00+02:00 --every PT1H30M
Config(day=datetime.date(2021, 2, 3), start=datetime.datetime(2021, 2, 3, 10, 0, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200))), every=datetime.timedelta(seconds=5400))
{'day': '2021-02-03', 'start': '2021-02-03T10:00:00+02:00', 'every': 'PT1H30M'}
A date, a datetime and a time read whatever their fromisoformat reads, and an offset is kept as written.
A duration is an ISO 8601 duration in days, hours, minutes and seconds (PT1H30M, P1DT12H, -PT30S, weeks too); a bare number is refused, since it carries no unit.
A timezone is a UTC offset, +02:00 or Z.
YAML and TOML files hold dates natively, and a date there is read as its text would be: start: 2021-02-03 is that day's midnight for a datetime, and a datetime is refused for a date, as on the command line.
Quote a time of day in YAML: YAML reads an unquoted 10:20 as the number 620, which the error points out.
dump() writes each as its ISO text, as above, so its output suits any file format.
dump_file() writes dates and datetimes as the native dates of a YAML or TOML file, and confarg.dump(config, native_types=confarg.YAML_NATIVE_TYPES) does the same for a YAML writer of your own.
Types¶
Types can be specified as leaf types. Take this configuration:
You can pass a built-in type, or any other type by its fully-qualified dotted path.
$ uv run type.py --value int
Config(value=<class 'int'>)
$ uv run type.py --value __main__.Config
Config(value=<class '__main__.Config'>)
When a class is specified, this class or any class that derives from it can be passed.
Let's modify our configuration:
$ # BaseClass can be passed
$ uv run base_class.py --value __main__.BaseClass
Config(value=<class '__main__.BaseClass'>)
$ # A derived class can also be passed
$ uv run base_class.py --value __main__.DerivedClass
Config(value=<class '__main__.DerivedClass'>)
$ # Error: a type that is not derived from BaseClass gets rejected
$ uv run base_class.py --value __main__.UnrelatedClass
...
Callables¶
Callables are also accepted as a special kind of leaf type. However, they are more involved than other leaf types, and we will spend four tutorials to go in depth into them in Tutorial #18, Tutorial #19, Tutorial #20, and Tutorial #21.
Custom leaf types¶
Confarg allows you to register custom leaf types via the confarg.register_leaf_type function.
This can help make configurations simpler to read and write.
Say we have a custom Int class that supports NaN values and that we want to treat as a leaf type.
We write a custom coercion function:
and register this coercion with confarg:
The Int type can now be used as a leaf type, just like the regular int type.
$ uv run custom_leaf_type.py --input 42
Config(input=Int(value=42))
$ uv run custom_leaf_type.py --input NaN
Config(input=Int(value=None))
Without leaf type registration, initializing a custom Int would require an init dict (--input.value 42) that would make its initialization different from that of plain integers.
Writing the value back¶
Registration makes Int a leaf in both directions: confarg.dump and confarg.dump_file write it as a single scalar rather than as an init dict.
How that scalar is spelled is decided by the serialize argument, the inverse of coerce:
Registration then takes the coercion and the serializer together:
serialize defaults to str, which is the wire form of types like IPv4Address.
Our Int is not one of them — str(Int(42)) is the debugging form Int(value=42), which coerce_int would refuse on the way back in — so we pass an explicit serializer, and a dumped configuration loads again unchanged.
A field that takes more than it holds¶
Sometimes a field holds an object, but a shorter spelling would do to configure it: the pattern of a Locator, or a handle into a registry of them.
Widening the field's type to Locator | str would let the configuration through, but every piece of code reading the field would then have to check which of the two it got.
A descriptor states both types in plain Python: its __set__ says what the field takes, its __get__ what it holds, and the conversion between them is its own.
class LocatorField:
"""Hold a Locator, given as one or as the pattern of one."""
def __set_name__(self, owner: type, name: str) -> None:
self._attr = "_" + name
def __get__(self, obj: object, objtype: Any = None) -> Locator:
if obj is None:
raise AttributeError # no default: the field is required
return getattr(obj, self._attr)
def __set__(self, obj: object, value: Locator | str) -> None:
setattr(obj, self._attr, Pattern(pattern=value) if isinstance(value, str) else value)
@dataclass
class Config:
"""Configuration whose locate field takes a str as well as a Locator."""
locate: LocatorField = LocatorField()
Type checkers read Config(locate="left_eye") as valid and config.locate as a Locator, and so does confarg: locate takes a Locator | str from every source, and the descriptor turns a string into a Pattern.
$ uv run descriptor.py --locate left_eye
Config(locate=Pattern(pattern='left_eye'))
$ uv run descriptor.py --locate.class __main__.Pattern --locate.pattern left_eye
Config(locate=Pattern(pattern='left_eye'))
What __get__ returns when its instance is None is the field's default; raising AttributeError there, as above, makes the field required.
confarg.dump writes what the field holds, the Locator, which reads back since the field takes a Locator too.