override_config

override_config#

override_config(cfg, copy=False, **kwargs)[source]#

Override elements of a (nested dict) configuration using dot notation.

Parameters:
  • cfg (dict) – Nested dictionary configuration.

  • copy (bool, optional) – If True, return a modified deep copy (original left untouched); otherwise cfg is modified in place. Default is False.

  • **kwargs – Override values, with keys in dot notation, e.g. **{'key1.key2.key3': newval}.

Returns:

dict – Modified configuration (cfg itself, or its copy if copy).

Raises:

KeyError – If a key does not already exist in cfg.

Examples

>>> cfg = dict(a=1, b=dict(c=2, d=3))
>>> override_config(cfg, **{'b.c': 4})
{'a': 1, 'b': {'c': 4, 'd': 3}}
>>> override_config(cfg, **{'b.e': 5})
Traceback (most recent call last):
...
KeyError: "Unknown key 'b.e'."

A whole sub-dictionary can be overridden at once:

>>> override_config(cfg, **{'b': dict(c=3, d=4)})
{'a': 1, 'b': {'c': 3, 'd': 4}}