Custom Handlers

When requesting a config-instance using get_config() it is possible to specify a custom file-handler using the handler keyword arg. For example:

from config_resolver import get_config
from config_resolver.handlers import json

result = get_config('foo', 'bar', handler=json)

Each handler has full control over the data type which is returned by get_config(). get_config always returns a named-tuple with two arguments:

  • config: This contains the object returned by the handler.
  • meta: This is a named-tuple which is generated by config_resolver and not modifyable by a handler. See The Meta Object.

A handler must implement the following functions/methods:

empty() → T

This function should return an empty config instance.

from_string(data: str) → T

This function should parse a string and return the corresponding config instance.

from_filename(filename: str) → T

This function should open a file at filename and return a parsed config instance.

get_version(instance: T) → str

This function should return the expected config version as string.

update_from_file(instance: T, filename: str) → None

This function should update the existing config instance with the configuration found in filename.

The INI and JSON handlers will update config instances by keeping the existing values and only updating the new-found values. This function could be overridden in a way that only the latest file will be kept (i.e. replacing configs instead of updating).

See the existing handlers in config_resolver.handler for some practical examples.