ConfigurationBase

class upsilonconf.ConfigurationBase(**kwargs: V)[source]

Interface for configuration objects.

This interface can be interpreted in essentially two ways:

  • a dictionary (or mapping) with attribute syntax, or

  • an object with indexing syntax.

On top of the combined feature set of dictionaries and attributes, this class provides convenient indexing, merging and conversions. Values of type dict (or other mapping types) will be automatically converted to configuration objects, giving rise to hierarchical configuration objects.

Added in version 0.7.0.

See also

PlainConfiguration

implementation of mutable configuration.

FrozenConfiguration

implementation of immutable configuration.

class FlatConfigView(config: ConfigurationBase)[source]

Flat view of configuration object.

class FlatItemsView(config: ConfigurationBase)[source]

Flat view of key-value pairs in configuration.

class FlatKeysView(config: ConfigurationBase)[source]

Flat view of keys in configuration.

class FlatValuesView(config: ConfigurationBase)[source]

Flat view of values in configuration.

keys() KeysView[source]
keys(*, flat: bool = False) KeysView | FlatKeysView

Get a view of this configuration’s keys.

Parameters:
flatbool, optional

If True, the hierarchy of this config is ignored. This means that instead of including subconfigs, the subconfigs are recursively flattened in the view. The subconfig-key and keys in the subconfig are combined using .-syntax, making them valid indices for this object. If False (default), a dict-like view is returned.

Returns:
keys_viewKeysView or FlatKeysView

The new view on the keys in this config.

See also

values

view on values

items

view on key-value pairs

Examples

The examples below work for any subclass of ConfigurationBase.

>>> from upsilonconf import PlainConfiguration as Config
>>> conf = Config(a=123, sub=Config(b="foo", c=None))
>>> list(conf.keys())
['a', 'sub']
>>> list(conf.keys(flat=True))
['a', 'sub.b', 'sub.c']
values() ValuesView[source]
values(*, flat: bool = False) ValuesView | FlatValuesView

Get a view of this configuration’s values.

Parameters:
flatbool, optional

If True, the hierarchy of this config is ignored. This means that instead of including subconfigs, the subconfigs are recursively flattened in the view. The subconfig-key and keys in the subconfig are combined using .-syntax, making them valid indices for this object. If False (default), a dict-like view is returned.

Returns:
values_viewValuesView or FlatValuesView

The new view on the values in this config.

See also

keys

view on keys

items

view on key-value pairs

Examples

The examples below work for any subclass of ConfigurationBase.

>>> from upsilonconf import PlainConfiguration as Config
>>> conf = Config(a=123, sub=Config(b="foo", c=None))
>>> list(conf.values())
[123, PlainConfiguration(b='foo', c=None)]
>>> list(conf.values(flat=True))
[123, 'foo', None]
items() ItemsView[source]
items(*, flat: bool = False) ItemsView | FlatItemsView

Get a view of this configuration’s key-value pairs.

Parameters:
flatbool, optional

If True, the hierarchy of this config is ignored. This means that instead of including subconfigs, the subconfigs are recursively flattened in the view. The subconfig-key and keys in the subconfig are combined using .-syntax, making them valid indices for this object. If False (default), a dict-like view is returned.

Returns:
items_viewItemsView or FlatItemsView

The new view on the key-value pairs in this config.

See also

keys

view on keys

values

view on values

Examples

The examples below work for any subclass of ConfigurationBase.

>>> from upsilonconf import PlainConfiguration as Config
>>> conf = Config(a=123, sub=Config(b="foo", c=None))
>>> list(conf.items())
[('a', 123), ('sub', PlainConfiguration(b='foo', c=None))]
>>> list(conf.items(flat=True))
[('a', 123), ('sub.b', 'foo'), ('sub.c', None)]
classmethod load(path: Path | str, *, overrides: Mapping[str, V] | Sequence[Tuple[str, V]] = (), key_mods: Mapping[str, str] | None = None, io: ConfigIO | None = None) Self[source]

Load configuration from a file.

Added in version 0.8.0.

Parameters:
pathPath or str

Path to a readable text file on disk.

overridesdict or sequence of tuples, optional

Collection of key-value pairs to update the original configuration with. This enables adding keys and overriding values for existing keys.

key_modsdict, optional

A mapping from key patterns to their respective replacement. With multiple patterns, longer patterns are replaced first.

ioConfigIO, optional

The IO used for parsing the configuration file to a dictionary. If not specified, the default IO will be used.

Returns:
configConfigurationBase

A configuration object with the values as provided in the file.

See also

from_dict

method used for key modifications

ConfigIO.read

read configuration file

save(path: Path | str, *, key_mods: Mapping[str, str] | None = None, io: ConfigIO | None = None)[source]

Save configuration to a file.

Added in version 0.8.0.

Parameters:
pathPath or str

Path to a writeable location on disk.

key_modsdict, optional

A mapping from key patterns to their respective replacement. With multiple patterns, longer patterns are replaced first.

ioConfigIO, optional

The IO used for writing a dictionary to the configuration file. If not specified, the default IO will be used.

See also

to_dict

method used for key modifications

ConfigIO.write

write configuration file

classmethod from_cli(args: Sequence[str] | None = None, *, parser: ConfigParser | ArgumentParser | None = None, key_mods: Mapping[str, str] | None = None, io: ConfigIO | None = None) Self | Tuple[Self, Namespace][source]

Create configuration from command-line arguments.

Added in version 0.8.0.

Parameters:
argssequence of str, optional

The list of arguments to parse. By default, arguments are taken from sys.argv.

parserArgumentParser or ConfigParser, optional

The CLI parser to use as a base for retrieving configuration options. If not specified, an empty parser will be created.

ioConfigIO, optional

Specifies how configuration files and command-line arguments are read. This argument is ignored if a ConfigParser is passed for parser.

Returns:
configConfigurationBase

A configuration object with keys and values as specified through the command line arguments.

nsNamespace, optional

A namespace object with non-configuration arguments. This is only returned if parser is given and not a ConfigParser object with return_ns == False.

See also

from_dict

method used for key modifications

ConfigParser.parse_cli

parse CLI arguments

classmethod from_dict(mapping: Mapping[str, V], *, key_mods: Mapping[str, str] | None = None) Self[source]

Create a configuration from another mapping.

In its simplest form, this method unpacks the dictionary and passes the key-value pairs as arguments to the constructor. The key_mods argument additionally allows to clean up keys.

Changed in version 0.8.0: key_mods can no longer be passed as positional argument.

Parameters:
mappingMapping[str, V]

The dictionary from which to create a configuration object.

key_modsMapping[str, str], optional

A mapping from key patterns to their respective replacement. With multiple patterns, longer patterns are replaced first.

Returns:
configConfigurationBase

A configuration object representing the original mapping where any occurrence of patterns in keys_mods in the original keys has been replaced.

See also

to_dict

inverse conversion from config to mapping.

__init__

regular constructor.

Examples

The examples below work for any subclass of ConfigurationBase.

>>> from upsilonconf import PlainConfiguration as Config

Without key_mods, the dictionary is equivalent to __init__.

>>> d = {"my key": "foo", "a key": 1}
>>> conf = Config.from_dict(d)
>>> conf
PlainConfiguration(my key='foo', a key=1)
>>> conf["my key"]
'foo'

By using the key_mods argument, keys can become more accessible.

>>> conf = Config.from_dict(d, key_mods={" ": "_"})
>>> conf
PlainConfiguration(my_key='foo', a_key=1)
>>> conf.my_key
'foo'

Flat ``dict``s can also be converted to a hierarchical config.

>>> conf = Config.from_dict(d, key_mods={" ": "."})
>>> conf
PlainConfiguration(my=PlainConfiguration(key='foo'), a=PlainConfiguration(key=1))

Multiple replacements can be combined in a single call.

>>> conf = Config.from_dict(d, key_mods={" ": "_", "e": "3"})
>>> conf
PlainConfiguration(my_k3y='foo', a_k3y=1)

Note that replacements are executed in order of length.

>>> conf = Config.from_dict(d, key_mods={"my ": "A", " ": "B"})
>>> conf
PlainConfiguration(Akey='foo', aBkey=1)
to_dict(*, key_mods: Mapping[str, str] | None = None, flat: bool = False) Dict[str, V][source]

Convert this configuration to a dictionary.

This method transfers the key-value pairs in this configuratio to a dictionary recursively (for hierarchical configurations). The key_mods argument additionally allows to modify keys. The flat argument allows to flatten hierarchical configurations.

Changed in version 0.8.0: key_mods can no longer be passed as positional argument.

Parameters:
key_modsMapping[str, str], optional

A mapping from key patterns to their respective replacement. With multiple patterns, longer patterns are replaced first.

flatbool, optional

Discard the hierarchy in this configuration object. When True, keys in subconfigurations are converted to dot-strings that are valid indices for this configuration.

Returns:
mappingdict[str, V]

A dict representing this configuration where any occurrence of patterns in keys_mods in the original keys has been replaced.

See also

from_dict

inverse conversion from mapping to config.

items

iterate over (flattened) key-value pairs.

Examples

The examples below work for any subclass of ConfigurationBase.

>>> from upsilonconf import PlainConfiguration as Config

For configurations without hierarchy, this method has the same effect as calling dict.

>>> conf = Config(my_key="foo", a_key=1)
>>> dict(conf)
{'my_key': 'foo', 'a_key': 1}
>>> conf.to_dict()
{'my_key': 'foo', 'a_key': 1}

For hierarchical configurations, the conversion is applied recursively.

>>> conf = Config(sub=conf)
>>> dict(conf)
{'sub': PlainConfiguration(my_key='foo', a_key=1)}
>>> conf.to_dict()
{'sub': {'my_key': 'foo', 'a_key': 1}}

The hierarchy can also be discarded using the flat argument.

>>> conf.to_dict(flat=True)
{'sub.my_key': 'foo', 'sub.a_key': 1}

By using the key_mods argument, keys can be made more readable.

>>> conf.to_dict(key_mods={"_": " "})
{'sub': {'my key': 'foo', 'a key': 1}}

Also, dot-strings from flattening can be replaced.

>>> conf.to_dict(flat=True, key_mods={".": "_"})
{'sub_my_key': 'foo', 'sub_a_key': 1}

Multiple replacements can be combined in a single call.

>>> conf.to_dict(key_mods={"_": " ", "e": "3"})
{'sub': {'my k3y': 'foo', 'a k3y': 1}}

Note that replacements are executed in order of length.

>>> conf.to_dict(key_mods={"my_": "A", "_": "B"})
{'sub': {'Akey': 'foo', 'aBkey': 1}}