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 to True (default) only fields from bases which are themselves templates are added to the template. If False, 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

bool

konfi.is_template_like(obj)

Check whether the given object is template-like.

Currently this includes templates and dataclasses.

Return type

bool

konfi.fields(obj)

Get the fields of a template-like instance or class.

Raises

TypeError – If the given object isn’t template-like.

Return type

Tuple[Field, …]

Returns

A tuple containing all fields of the template.

konfi.get_field(obj, attr)

Get the field for an attribute from a template-like instance or class.

Raises

TypeError – If the given object isn’t template-like.

Return type

Optional[Field]

Returns

The field for the attribute or None if no such field exists.

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).

  • comment (Optional[str]) – Comment for the field.

  • 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.

key

Corresponding config key to use.

Type

Optional[str]

comment

Comment for the field.

Type

Optional[str]

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.

property required

Checks whether the field must be set.

Return type

bool

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

Any

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.

attribute

Name of the attribute the field belongs to.

Type

str

key

Name of the config key.

Type

str

value_type

Expected type of the field.

Type

Type

property optional_type

Optional[str]).

Type

Whether the value type is optional (ex

Return type

bool

property required

Checks whether the field must be set.

Return type

bool

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

Any

konfi.ValueFactory = typing.Callable[[], typing.Any]

Callable which when called, returns a value.

konfi.MISSING = MISSING

Sentinel representing a missing value.

This is used to represent the lack of a default value, because None would lead to a conflict.

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.

abstract load_into(obj, template)

Load the config into the given object according to the template.

Raises

Exception – If the config couldn’t be loaded.

Return type

None

@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’t True.

konfi.has_file_loader(ext)

Check whether the given extension has a file loader associated.

Parameters

ext (str) – File extension including the leading dot.

Return type

bool

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 a FileLoaderType (which can be a konfi.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 unless ignore_no_loader is set to True.

Parameters
  • path (str) – Path of config file to load.

  • ignore_no_loader (bool) – If set to True 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 to True and the wrapped source raises a FileNotFoundError, 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 is False.

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.

Parameters
  • path (str) – File path to load file from.

  • ignore_not_found (bool) – When this is set to true and the config file couldn’t be found at the given path, no error is raised and nothing is loaded.

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 convert

  • target (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.has_converter(target)

Check whether the given target type has a converter.

Return type

bool

@konfi.register_converter(*types)

Decorator which registers the underlying type as a converter.

This can either be a converter function (ConverterFunc), a ConverterABC 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 for ComplexConverterABC 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
  • conv (Union[ConverterABC[~CT], Type[ConverterABC[~CT]], Callable[[Any], ~CT]]) – Converter to unregister

  • *types – Types to unregister converter from. If empty, the converter is unregistered from all types.

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.

abstract convert(value, target)

Convert the given value to the target type.

Parameters
  • value (Any) – Value to convert.

  • target (Type[~CT]) – Type to convert the value to.

Raises

Exception – When the conversion failed.

Return type

~CT

Returns

Converted value.

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.

source

Source that tried to load the config.

Type

SourceABC

template

Template that was to be loaded.

Type

type

error

Original error that was raised. This is provided for convenience.

Type

Exception

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.

path

Path to the origin of the exception.

Type

List[str]

property path_str

Get the path as a string.

Return type

str

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

konfi.Field

exception konfi.MultiPathError(path, errors, msg)

Bases: konfi.source.PathError

Exception grouping multiple PathError instances.

errors

Grouped path errors.

Type

List[PathError]

exception konfi.NoDefaultValue

Bases: Exception

Exception for when a default value is expected, but doesn’t exist.

exception konfi.ConversionError

Bases: Exception

Exception raised if a conversion failed.