API Reference¶
Template¶
-
@
konfi.
template
(*, template_bases_only=True)¶ Decorator to convert the given class to a template.
This parses the decorated class into a template which can be used to load the config. The fields are loaded from the annotations from the class. If an attribute has a value it is used as the default value, unless it’s an unbound field (see
konfi.field
) which is used directly and the class variable is replaced.- Parameters
template_bases_only (
bool
) – If set toTrue
(default) only fields from bases which are themselves templates are added to the template. IfFalse
, all annotations from all bases are considered as being part of the class itself.- Raises
ValueError – If the decorated object isn’t a class.
TypeError – If one of the fields has an invalid type.
-
konfi.
is_template
(obj)¶ Check whether the given object is a template instance or class.
- Return type
-
konfi.
is_template_like
(obj)¶ Check whether the given object is template-like.
Currently this includes templates and dataclasses.
- Return type
Field¶
-
konfi.
field
(*, key=None, comment=None, default=MISSING, factory=None, converter=None)¶ Specify a field options.
This creates an unbound field which is later upgraded to a bound field when the template is created. The class variable is also replaced with the default value of the field and if no default value exists, it is removed.
- Parameters
key (
Optional
[str
]) – Config key to use (instead of the attribute name).default (
Any
) – Default value for the field.factory (
Optional
[Callable
[[],Any
]]) – Factory method to use to get the default value. You can’t set both the default and the factory value.converter (
Union
[ConverterABC
[~CT],Type
[ConverterABC
[~CT]],Callable
[[Any
], ~CT],None
]) – Custom converter to use.
- Raises
ValueError – If both factory and default value are specified.
- Return type
UnboundField
- Returns
An unbound field.
-
class
konfi.
UnboundField
(*, key=None, comment=None, default_value=MISSING, default_factory=None, converter=None)¶ A field that hasn’t been bound to a template.
Note that an unbound field is usually created using the
field
function, not directly.-
default_value
¶ The default value of the field. The value
MISSING
is used if no default value exists.- Type
Any
-
default_factory
¶ Factory to call to get the default value.
- Type
Optional[ValueFactory]
-
converter
¶ Converter to use.
- Type
Optional[ConverterType]
- Raises
ValueError – If both factory and default value are specified.
-
get_default
()¶ Get the default value of the field.
This uses either the default value or calls the default factory.
- Raises
NoDefaultValue – If the field doesn’t have a default value.
- Return type
-
-
class
konfi.
Field
(*, attribute, key=None, comment=None, value_type, default_value=MISSING, default_factory=None, converter=None)¶ A field of a template.
Field is a superset of
UnboundField
meaning it inherits all attributes and arguments.-
value_type
¶ Expected type of the field.
- Type
Type
-
property
optional_type
¶ Optional[str]).
- Type
Whether the value type is optional (ex
- Return type
-
get_default
()¶ Get the default value of the field.
This uses either the default value or calls the default factory.
- Raises
NoDefaultValue – If the field doesn’t have a default value.
- Return type
-
-
konfi.
ValueFactory
= typing.Callable[[], typing.Any]¶ Callable which when called, returns a value.
Loader¶
-
konfi.
set_sources
(*sources)¶ Set the sources to use when loading.
- Return type
None
-
konfi.
load
(template)¶ Load the config for the given template.
- Parameters
template (
Union
[Type
[~TT], ~TT]) – Template to load from the sources. If this is already an instance of the template, then the config is loaded into the instance.- Raises
ValueError – If no sources are set.
TypeError – If the given template isn’t template-like.
SourceError – If one of the sources fails to load the config.
- Return type
~TT
-
class
konfi.
Loader
¶ Loads the config from sources.
-
set_sources
(*sources)¶ Set the sources to use when loading.
- Return type
None
-
load
(template)¶ Load the config for the given template.
- Parameters
template (
Union
[Type
[~TT], ~TT]) – Template to load from the sources. If this is already an instance of the template, then the config is loaded into the instance.- Raises
ValueError – If no sources are set.
TypeError – If the given template isn’t template-like.
SourceError – If one of the sources fails to load the config.
- Return type
~TT
-
Source¶
-
class
konfi.
SourceABC
¶ Abstract base class of a source which can load the config.
-
@
konfi.
register_file_loader
(*file_types, replace=False)¶ Decorator to register a file loader.
The decorated object must be a
FileLoaderType
.- Parameters
*file_types – File extensions (including the dot) to assign to the decorated source.
replace (
bool
) – Whether to replace existing file loaders if an extension is already registered.
- Raises
TypeError – If the decorated value isn’t a file loader constructor
ValueError – If one of the file types is already registered and
replace
isn’tTrue
.
-
konfi.
has_file_loader
(ext)¶ Check whether the given extension has a file loader associated.
-
class
konfi.
FileLoader
(path, *, ignore_no_loader=False, ignore_not_found=False, **kwargs)¶ A higher order source which uses other sources under the hood.
The source uses the file extension of the given path to determine which source to use. This is done by providing the
register_file_loader
decorator which can be used to register aFileLoaderType
(which can be akonfi.SourceABC
) for the given extensions.Supported extensions by the built-in sources:
YAML: .yml, .yaml, .json
TOML: .toml
The file loader is determined as soon as the constructor is called, so if there is no file loader for the given extension a
ValueError
is raised unlessignore_no_loader
is set toTrue
.- Parameters
path (
str
) – Path of config file to load.ignore_no_loader (
bool
) – If set toTrue
and no loader could be found for the given path, the source turns into a dummy source and doesn’t load anything.ignore_not_found (
bool
) – If set toTrue
and the wrapped source raises aFileNotFoundError
, it is ignored.**kwargs – Keyword arguments to pass to the file loader constructor.
- Raises
ValueError – If no file loader was found for the given path and
ignore_no_loader
isFalse
.
-
class
konfi.
Env
(prefix='', *, decoder='python', name_builder=<function build_env_name>)¶ Source which loads the config from environment variables.
The env source is different from most sources because it walks through the config template and looks for the corresponding environment variable instead of the other way around. This means that with the exception of template-like objects it’s not possible to set sub values directly. For example, you can’t update a specific key of a dictionary using an environment variable using a specific environment variable, only the entire value (i.e. dictionary) can be set.
- Parameters
prefix (
str
) – Prefix to prepend to all variable names. This can be used to prevent name collisions and ensure that the variables were set with the right intent.decoder (
Union
[str
,Callable
[[str
],Any
]]) –Decoder used to interpret the values of the environment variables. There are three built-in decoders:
raw: Values are interpreted as strings.
python: Values are (safely) interpreted as if they were Python literals.
yaml: Values are interpreted as YAML. This is by far the most powerful and convenient decoder. For example, it doesn’t require the use of quotation marks to escape strings.
You can also pass your own decoder with the type
Decoder
which is just a function that takes a string and returns the decoded version.The default is the python decoder.
name_builder (
Callable
[[List
[str
]],str
]) –Function that combines the path segments of a field to the name of the corresponding environment variable (ex: [“database”, “main”, “url”] -> “DATABASE_MAIN_URL”).
The default is the
build_env_name
function which removes non-alphanumeric characters and underscores from the path segments as well as stripping leading numbers. The segments are then joined using underscores. For example [“a_b@”, “1c_d”] would be turned into “AB_CD”.
-
class
konfi.
TOML
(path, *, ignore_not_found=False, **_)¶
-
class
konfi.
YAML
(path, *, ignore_not_found=False, **_)¶ Source which loads the config from YAML files.
Converter¶
-
konfi.
convert_value
(value, target, *, exclude_converters=None)¶ Convert the value to the given type.
If no converter was found but the target type is a class, a conversion using the constructor is attempted.
If the value already has the target type, it is returned even if no converters are found.
- Parameters
value (
Any
) – Value to converttarget (
Type
[~T]) – Target type to convert to.exclude_converters (
Optional
[Set
[Union
[ConverterABC
[~CT],Type
[ConverterABC
[~CT]],Callable
[[Any
], ~CT]]]]) – Set of converter types to exclude. Note that this only excludes the converters from this call, if a converter further down the line calls this function the exclusion no longer applies.
- Raises
ConversionError – If the conversion failed.
- Return type
~T
-
@
konfi.
register_converter
(*types)¶ Decorator which registers the underlying type as a converter.
This can either be a converter function (
ConverterFunc
), aConverterABC
class or an instance thereof. If the converter is a class, it is instantiated only when the conversion takes place. The constructor will be called without any arguments. There is an exception forComplexConverterABC
classes, as they are instantiated upon registration.- Parameters
*types – Types which the converter converts to. This is ignored if the converter is a complex converter, but required otherwise.
- Raises
TypeError – If the decorated object isn’t a converter type.
ValueError – If no types are provided but the converter isn’t a complex converter or vice versa.
-
konfi.
unregister_converter
(conv, *types)¶ Unregister the given converter from the given types.
- Parameters
- Raises
TypeError – If the given converter is a complex converter and types are given.
- Return type
None
-
konfi.
ConverterType
= typing.Union[konfi.converter.ConverterABC, typing.Type[konfi.converter.ConverterABC], typing.Callable[[typing.Any], ~CT]]¶ Type of a converter.
-
konfi.
ConverterFunc
= typing.Callable[[typing.Any], ~CT]¶ Callable which converts the given value to a type.
-
class
konfi.
ConverterABC
¶ Converter which converts a value to a type.
Usually a normal converter only converts to one specific type, or a group of closely related types.
-
class
konfi.
ComplexConverterABC
¶ Bases:
konfi.converter.ConverterABC
,abc.ABC
Notes
Unlike
ConverterABC
converters, the complex converter will be converted to a singleton instance upon registration.
Exceptions¶
-
exception
konfi.
SourceError
(source, template, error)¶ Bases:
Exception
Exception raised when a source fails to load the config.
-
exception
konfi.
PathError
(path, msg)¶ Bases:
Exception
General exception in a template path.
The path represents the config keys, which is not necessarily the same as the attributes.
-
backtrace_path
(part)¶ Add a part to the path.
- Return type
None
-
-
exception
konfi.
FieldError
(path, field, msg)¶ Bases:
konfi.source.PathError
Exception for a particular field.
-
field
¶ Field which caused the exception.
- Type
-
-
exception
konfi.
MultiPathError
(path, errors, msg)¶ Bases:
konfi.source.PathError
Exception grouping multiple
PathError
instances.