API Documentation

The API documentation covers the full public api for the library including examples for more complicated features. The configclass decorator is described followed by pluggable sources of configuration values, and finally convenience enums and data type conversion functionality.

Configclass

configclasses.configclass(source: Source=None, sources: List[Source]=None)[source]

Turn a class into a configclass with the default EnvironmentSource used.

For example, configuring the host and port for a web application might look like this:

>>> from configclasses import configclass
>>> @configclass
... class Configuration:
...     HOST: str
...     PORT: int

Turn a class into a configclass using the user provided source or sources list.

Parameters:
  • source – single Source used to fetch values.
  • sources – list of Source used to fetch values, prioritized from first to last.
Raises:

ValueError – The user must pass either the source or a list of sources. It is an error to provide both.

Configuring the host and port for a web application using both command line arguments and environment variables as sources:

>>> from configclasses import configclass, sources
>>> env_source = EnvironmentSource()
>>> cli_source = CommandLineSource()
>>> @configclass(sources=[cli_source, env_source])
... class Configuration:
...     HOST: str
...     PORT: int

Because the cli_source comes after the env_source in the list of sources, it will be prioritized when fetching values that are found in both sources.

Decorate your configuration classes with the configclass decorator to turn them into Configuration Classes.

The returned configclass will have a .reload() method present, that can be used to reload values from configuration sources on demand. This reload affects all instances of the configclass you are reloading.

configclasses.field(converter=None, default=MISSING, default_factory=MISSING, init=True, repr=True, hash=None, compare=True, metadata=None)[source]

This function can be used if the field differs from the default functionality. It is the same as the field function in the dataclasses module except that it includes a converter argument that can be used to convert from a primitive type to a more complex type such as a dict or custom class.

Parameters:
  • converter – is a function that takes a single argument and constructs a return value that is the same as the conficlass field’s type annotation.
  • converter – is a function that takes a single argument and returns True or False depending on whether that argument is considerd a valid value.
  • default – is the default value of the field.
  • default_factory – is a 0-argument function called to initialize a field’s value.
  • init – if True, the field will be a parameter to the class’s __init__() function.
  • repr – if True, the field will be included in the object’s repr().
  • hash – if True, the field will be included in the object’s hash().
  • compare – if True, the field will be used in comparison functions.
  • metadata – if specified, must be a mapping which is stored but not otherwise examined by dataclass.
Raises:

ValueError – It is an error to specify both default and default_factory.

Sources

Source classes know how to fetch configuration values from all kinds of different sources of configuration values. A number of Source classes are provided by the library, and users can implement their own sources.

TODO: link to documentation on implementing custom sources.

Builtin sources:

class configclasses.sources.EnvironmentSource(namespace=None, environ=os.environ)[source]

Get configuration values from case insensitive environment variables.

Parameters:
  • namespace – An optional string prefix to match on with environment variables.
  • environ – A different source of environment variables can be passed if you don’t want to use os.environ.

If namespace is provided, only environment variable names that start with the namespace value will be considered. The namespace is also stripped off the variable name before it is stored.

reload()[source]

Fetch and parse values from the environment dict and store them.

class configclasses.sources.DotEnvSource(path='.env', filehandle=None, namespace=None)[source]

Get configuration values from a .env (dotenv) formatted file.

Parameters:
  • path – path to read from.
  • filehandle – open file handle to read from.
  • namespace – string prefix for values this sources will fetch from.
Raises:

ValueError – It is an error if both path and filehandle are defined or neither path nor filehandle are defined.

reload()

Fetch and parse values from the file source and store them.

If a path was provided to the source, the path will be reopened and read. If a filehandle was provided and the handle supports seeking, it will seek to the position the handle was at when passed to the source. If it does not support seeking, it will attempt to read from the current position.

It is up to the user to ensure that filehandles will act correctly given the above rules

class configclasses.sources.CommandLineSource(argparse=None, argv=sys.argv)[source]

Get configuration values from command line arguments. Adds command line arguments for each field in the associated configclass.

Parameters:
  • argparse – Optionally pass in a preexisting argparse.ArgumentParser instance to add to an existing set of command line arguments rather than only using auto-generated command line arguments.
  • argv – Optionally pass a custom argv list. Most useful for testing.
reload()

Child classes that have a sensible reload strategy should override this method

class configclasses.sources.JsonSource(path=None, filehandle=None, namespace=None)[source]

Get configuration values from a json encoded file or filehandle.

Parameters:
  • path – path to read from.
  • filehandle – open file handle to read from.
  • namespace – list of keys or indices used to access a nested configuration object.
Raises:

ValueError – It is an error if both path and filehandle are defined or neither path nor filehandle are defined.

Namespacing for json sources is best described by example:

>>> json_value = """ {
...     "nested": {
...         "configuration": {
...             "FOO": "foo_value",
...             "BAR": "bar_value",
...         }
...     }
... }"""
>>> namespace = ["nested", "configuration"]

A JsonSource that reads a file with the contents of json_value with the namespace defined above would only consider the keys “FOO” and “BAR” as configuration values in scope.

reload()

Fetch and parse values from the file source and store them.

If a path was provided to the source, the path will be reopened and read. If a filehandle was provided and the handle supports seeking, it will seek to the position the handle was at when passed to the source. If it does not support seeking, it will attempt to read from the current position.

It is up to the user to ensure that filehandles will act correctly given the above rules

class configclasses.sources.TomlSource(path=None, filehandle=None, namespace=None)[source]

Get configuration values from a .toml file.

Parameters:
  • path – path to read from.
  • filehandle – open file handle to read from.
  • namespace – optional list of nested section to search for configuration fields
Raises:

ValueError – It is an error if both path and filehandle are defined or neither path nor filehandle are defined.

reload()

Fetch and parse values from the file source and store them.

If a path was provided to the source, the path will be reopened and read. If a filehandle was provided and the handle supports seeking, it will seek to the position the handle was at when passed to the source. If it does not support seeking, it will attempt to read from the current position.

It is up to the user to ensure that filehandles will act correctly given the above rules

class configclasses.sources.IniSource(path=None, filehandle=None, namespace=None)[source]

Get configuration values from a .ini file.

Parameters:
  • path – path to read from.
  • filehandle – open file handle to read from.
  • namespace – optional section to search for configuration fields
Raises:

ValueError – It is an error if both path and filehandle are defined or neither path nor filehandle are defined.

Note: Python ini parsing is case insensitive.

reload()

Fetch and parse values from the file source and store them.

If a path was provided to the source, the path will be reopened and read. If a filehandle was provided and the handle supports seeking, it will seek to the position the handle was at when passed to the source. If it does not support seeking, it will attempt to read from the current position.

It is up to the user to ensure that filehandles will act correctly given the above rules

class configclasses.sources.ConsulSource(root, namespace="", http=requests)[source]

Get configuration values from a remote consul key value store.

Parameters:
  • root – The address of the consul api to use. Don’t forget to include the scheme (http or https)!
  • namespace – The consul kv namespace from which to fetch fields.
  • http – http library used to make get requests. Defaults to using requests.
reload()[source]

Child classes that have a sensible reload strategy should override this method

Enums

Common configuration enums provided for user convenience. However, any subclass of python’s enum.Enum will work as expected.

class configclasses.enums.LogLevel(Enum)[source]

Python logging module log level constants represented as an enum.Enum.

NotSet = logging.NOTSET
Debug = logging.DEBUG
Info = logging.INFO
Warning = logging.WARNING
Error = logging.ERROR
Critical = logging.CRITICAL
class configclasses.enums.Environment(Enum)[source]

Common environment names.

Development = 0
Test = 1
Staging = 2
Production = 3

Conversions

Conversion functions that can be specified as the converter in a configclass field.

configclasses.conversions.csv_list(value: str) → list[source]

csv_lists are comma separated values. Whitespace around a value is stripped unless text is quoted. Empty values are skipped.

An example usage:

>>> csv_list("a,b,c")
["a", "b", "c"]

Typically it is used in specifying a configclass:

>>> @configclass
... class Configuration:
...     LIST: list = field(converter=csv_list)

Then a string of values will be converted into a list of strings in the Configuration class.

configclasses.conversions.csv_pairs(value: str) → dict[source]

Kv lists are comma separated pairs of values where a pair is defined as "key=value". Whitespace around a key or value is stripped unless text is quoted. Empty pairs are skipped.

Raises:ValueError – on a malformed key value pair.

An example usage:

>>> csv_pairs("a=1,b=2")
{"a": "1", "b": "2"}

Typically it is used in specifying a configclass:

>>> @configclass
... class Configuration:
...     PAIRS: dict = field(converter=csv_pairs)

Then a string of key=value pairs will be converted into a dictionary in the Configuration class.