Configuration parsing and validation.

This module provides parse_config which turns a dictionary of stringy keys and values into a structured and typed configuration object.

For example, an INI file like the following:

simple = true
cards = clubs, spades, diamonds
nested.once = 1
nested.really.deep = 3 seconds
some_file = /var/lib/whatever.txt
sample_rate = 37.1%
interval = 30 seconds

Might be parsed like the following. Note: when running under the baseplate server, The config_parser.items(...) step is taken care of for you and raw_config is passed as the only argument to your factory function.

>>> raw_config = dict(config_parser.items("app:main"))

>>> CARDS = config.OneOf(clubs=1, spades=2, diamonds=3, hearts=4)
>>> cfg = config.parse_config(raw_config, {
...     "simple": config.Boolean,
...     "cards": config.TupleOf(CARDS),
...     "nested": {
...         "once": config.Integer,
...         "really": {
...             "deep": config.Timespan,
...         },
...     },
...     "some_file": config.File(mode="r"),
...     "optional": config.Optional(config.Integer, default=9001),
...     "sample_rate": config.Percent,
...     "interval": config.Fallback(config.Timespan, config.Integer),
... })

>>> print(cfg.simple)

>>> print(
[1, 2, 3]

>>> print(cfg.nested.really.deep)

>>> cfg.some_file.close()

>>> cfg.sample_rate

>>> print(cfg.interval)


baseplate.lib.config.parse_config(config, spec)[source]

Parse options against a spec and return a structured representation.


ConfigurationError The configuration violated the spec.

Return type:



A structured configuration object.

Value Types

Each option can have a type specified. Some types compose with other types to make complicated expressions.


A raw string.

Return type:str

A floating-point number.

Return type:float
baseplate.lib.config.Integer(text=None, base=10)[source]

An integer.

To prevent mistakes, this will raise an error if the user attempts to configure a non-whole number.

Parameters:base (int) – (Optional) If specified, the base of the integer to parse.
Return type:Union[int, Callable[[str], int]]

True or False, case insensitive.

Return type:bool

A remote endpoint to connect to.

Returns an EndpointConfiguration.

If the endpoint is a hostname:port pair, the family will be socket.AF_INET and address will be a two-tuple of host and port, as expected by socket.

If the endpoint contains a slash (/), it will be interpreted as a path to a UNIX domain socket. The family will be socket.AF_UNIX and address will be the path as a string.

Return type:EndpointConfiguration

A span of time.

This takes a string of the form “1 second” or “3 days” and returns a datetime.timedelta representing that span of time.

Units supported are: milliseconds, seconds, minutes, hours, days.

Return type:timedelta

A base64 encoded block of data.

This is useful for arbitrary binary blobs.

Return type:bytes

A path to a file.

This takes a path to a file and returns an open file object, like returned by open().

Parameters:mode (str) – an optional string that specifies the mode in which the file is opened.
Return type:Callable[[str], Io[AnyStr]]

A percentage.

This takes a string of the form “37.2%” or “44%” and returns a float in the range [0.0, 1.0].

Return type:float

A Unix user name.

The parsed value will be the integer user ID.

Return type:int

A Unix group name.

The parsed value will be the integer group ID.

Return type:int

One of several choices.

For each option, the name is what should be in the configuration file and the value is what it is mapped to.

For example:

OneOf(hearts="H", spades="S")

would parse:



Return type:Callable[[str], ~T]

A comma-delimited list of type T.

At least one value must be provided. If you want an empty list to be a valid choice, wrap with Optional().

Return type:Callable[[str], Sequence[~T]]

If you need something custom or fancy for your application, just use a callable which takes a string and returns the parsed value or raises ValueError.

Combining Types

These options are used in combination with other types to form more complex configurations.

baseplate.lib.config.Optional(item_parser, default=None)[source]

An option of type T, or default if not configured.

Return type:Callable[[str], Optional[~T]]
baseplate.lib.config.Fallback(primary_parser, fallback_parser)[source]

An option of type T1, or if that fails to parse, of type T2.

This is useful for backwards-compatible configuration changes.

Return type:Callable[[str], ~T]
baseplate.lib.config.DictOf(*args, **kwds)[source]

A group of options of a given type.

This is useful for providing data to the application without the application having to know ahead of time all of the possible keys.

[app:main] = 1383890000 = 1317610000 = 325165000 = 263447000 = 207645000
>>> cfg = config.parse_config(raw_config, {
...     "population": config.DictOf(config.Integer),
... })

>>> len(cfg.population)

>>> cfg.population["br"]

It can also be combined with other configuration specs or parsers to parse more complicated structures:

[app:main] = 1383890000 = Beijing = 1317610000 = New Delhi = 325165000 = Washington D.C. = 263447000 = Jakarta = 207645000 = Brasília
>>> cfg = config.parse_config(raw_config, {
...     "countries": config.DictOf({
...         "population": config.Integer,
...         "capital": config.String,
...     }),
... })

>>> len(cfg.countries)

>>> cfg.countries["cn"].capital

>>> cfg.countries["id"].population

Data Types

class baseplate.lib.config.EndpointConfiguration[source]

A description of a remote endpoint.

This is a 2-tuple of (family and address).

One of socket.AF_INET or socket.AF_UNIX.
An address appropriate for the family.

Add a new parser

class baseplate.lib.config.Parser[source]

Base class for configuration parsers.


exception baseplate.lib.config.ConfigurationError(key, error)[source]

Raised when the configuration violates the spec.