Setting types
When a Setting
is defined, a type is also declared. By default, the value of a Setting
is str
, but any class or function that accepts a single parameter and returns a class instance can be
used. The class or function passed to _type will be called with the value to process as its only parameter.
Also take a look at the static typing support with Type annotations.
Built-in interpretation
Special cases are added to support dict
, list
, tuple()
and bool
, which are
processed by ast
. The implementation can be found in the unrepr
method in omniconf.config
:
- omniconf.config.unrepr(src: Any, _type: Callable[[...], Any]) Any [source]
Returns an interpreted value based on
src
. Ifsource
is already an instance of_type
, no interpretation is performed.
This means that a Setting declared as such:
from omniconf import setting
setting("items", _type=list)
Which is provided by a backend with the following string:
"['foo', 'bar', 'baz']"
Will return a list that looks like this:
from omniconf import config
print(config("items"))
# ['foo', 'bar', 'baz']
For detailed information, see the ast
documentation.
Custom interpretation and types
The most simple custom type looks like this:
def custom_type(src):
return src
This example simply takes the input as provided, and returns it as-is. Custom types are not limited to functions, classes can also be used. Any class that has exactly one (mandatory) parameter is valid):
class CustomType:
def __init__(self, src, foo=bar):
self.src = src
Some custom types are provided with omniconf, which may be used as-is, but also serve as examples.
Enum
- omniconf.types.enum(values: Sequence[str]) Callable[[str], str] [source]
Returns the original value if it is present in values, otherwise raises a RuntimeError.
enum_func = enum(["foo", "bar"]) print(enum_func("foo")) # "foo" print(enum_func("baz")) # ... # RuntimeError: Invalid value specified, must be one of: foo, bar
Separator Sequence
A somewhat fancy name for what one might normally call a comma separated list. The implementation is not limited to just commas however, and can use any string.
- omniconf.types.separator_sequence(separator: str) Callable[[str | Sequence[str]], Sequence[str]] [source]
Returns a function that parses a string value, separates it into parts and stores it as a read-only sequence:
parser = separator_sequence(",") print(parser("a,b,c")) # ['a', 'b', 'c']
If the input value is already a sequence (but not a string), the value is returned as is. The sequence is an instance of
SeparatorSequence
, and can be used as one would normally use a (read-only) tuple or list.