Converters¶
Converters are one of the core aspects of konfi. Converters make it possible to provide full type-safety to templates.
You can add new converters by using the konfi.register_converter
decorator or simply passing the converter argument to konfi.field
.
Since last registered converters are used first, you can overwrite a
built-in converter by registering a new converter for the same type
(Regardless of complex or not). The old converter(s) will be used as a
fallback if the new one raises an exception.
Converters should be stable i.e. if a value already has the correct type, the converter should return the same value (not necessarily the same value by identity, but by equality).
Builtin converters¶
Type |
Notes |
---|---|
|
Always returns |
Returns the value directly. |
|
Implemented by calling the type with the value. |
|
If the value is already iterable, it is returned directly, unless it is a string. Everything else is wrapped in a list and returned. |
|
Implemented by converting to an |
|
If the value is already a |
|
Implemented by converting to a |
|
|
Returns value directly if it’s already in the union, otherwise returns the first successful conversion result of trying each type from left to right. |
|
For n-tuples (tuples with a limited amount of items) each item is converted to the corresponding type. This requires that the lengths of the tuples are equal. Variadic tuples (tuples with an unspecified amount of items) are handled by converting each item to the value type. |
|
Works for all subtypes like |
|
Works analogous to |
Template-like |
Exists mainly for templates in containers like
|
Tries to find the appropriate member in the following order:
|