API

ResConfig Object

class resconfig.ResConfig(default=None, config_files=None, envvar_prefix='', load_on_init=True, merge_config_files=True, watchers=None)

Bases: resconfig.watchers.Watchable, resconfig.io.io.IO, resconfig.clargs.CLArgs

An application resource configuration.

This object holds the state and the internal data structure for the configuration.

Parameters
add_arguments_to_argparse(parser, prefix='', ignore=None)

Add config arguments to ArgumentParser.

The method add to the parser arguments that exist in the default config supplied on the instantiation of ResConfig object. The long option will be “-”-delimited for nested keys, e.g., config["foo.bar"] will be mapped to --foo-bar. If prefix is supplied, the prefix is prepended to the long option, e.g., --prefix-foo-bar.

To prevent the method from adding arguments to the parser for some keys, supply ignore with a set of keys to ignore, e.g., {"foo.bar"}, so that --foo-bar will not be added.

Parameters
  • parser (ArgumentParser) – Parser object to which config arguments are added.

  • prefix (str) – Argument prefix.

  • ignore (Optional[Set[str]]) – Config keys to ignore.

deregister(key, func=None)

Deregister the watch function for the key.

get(key, default=None)

Return the config value for key if it exists, else default.

Parameters
Return type

Any

Returns

The value found for the key.

load()

Load the prepared config.

prepare_from_argparse(args, config_file_arg=None, prefix='', keymap=None)

Prepare config from ArgumentParser result.

See the docstring of add_arguments_to_argparse() for the rule on how parser long options map to config keys. If long options do not directly map to config keys by that rule, you can supply prefix or keymap to define your own mapping. For example, if you want to map --long-opt (which would be parsed as the long_opt attribute) to the foo.bar config key, use {"long_opt": "foo.bar"} for keymap.

If you want to allow config file(s) to be specified through ArgumentParser, specify the attribute name for the argument to config_file_arg.

Parameters
  • args (Namespace) – Parse result returned from parse_args().

  • config_file_arg (Optional[str]) – The attribute name for config files.

  • prefix (str) – Argument prefix.

  • keymap (Optional[Dict[str, str]]) – Key mapping from the parsed argument name to the config key.

register(key, func)

Register the watch function for the key.

reload()

Trigger all watch functions using the current configuration.

Note that the watch functions for the keys that do not exist in the current configuration will not be triggered.

replace(conf)

Perform replacement of config.

Parameters

conf (dict) – Config for replacement.

reset()

Reset config to default.

save_to_file(filename)

Experimental: Save config to the file.

The file type is inferred from the filename extension.

save_to_ini(filename)

Experimental: Save config to the INI file.

save_to_json(filename)

Experimental: Save config to the JSON file.

save_to_toml(filename)

Experimental: Save config to the TOML file.

save_to_yaml(filename)

Experimental: Save config to the YAML file.

unload()

Empty the configuration.

update(conf)

Perform update of config.

Parameters

conf (dict) – Config to update with.

update_from_file(filename)

Update config from the file.

The file type is inferred from the filename extension.

update_from_files(paths, merge=False)

Update config from files.

How the config is constructed depends on the merge flag. If True, the files are searched in the reverse order, and the configs are read from all existing files and merged in that order. If False, then the files are searched for in the order given in paths, and the first existing file provides the config to be read (and the rest are ignored).

Parameters
  • paths (List[Union[str, Path]]) – A list of config file paths.

  • merge – The flag for the merge mode; see the function description.

update_from_ini(filename)

Update config from the INI file.

update_from_json(filename)

Update config from the JSON file.

update_from_toml(filename)

Update config from the TOML file.

update_from_yaml(filename)

Update config from the YAML file.

watch(key)

Decorate a function to make it a watch function for the key.

Return type

Callable[[Action, Any, Any], None]

ConfigPath Object

class resconfig.io.paths.ConfigPath(*args, **kwargs)

Bases: pathlib.PosixPath

Path for configuration file.

class resconfig.io.paths.INIPath(*args, **kwargs)

Bases: resconfig.io.paths.ConfigPath

Wrapper for INI config file path.

class resconfig.io.paths.JSONPath(*args, **kwargs)

Bases: resconfig.io.paths.ConfigPath

Wrapper for JSON file path.

class resconfig.io.paths.TOMLPath(*args, **kwargs)

Bases: resconfig.io.paths.ConfigPath

Wrapper for TOML file path.

class resconfig.io.paths.YAMLPath(*args, **kwargs)

Bases: resconfig.io.paths.ConfigPath

Wrapper for YAML file path.

Actions

class resconfig.actions.Action(value)

Action performed by the update method.

The watch function receives this value as its first argument to change its behavior based on the action.

ADDED = 1

The item at the key has been added.

MODIFIED = 2

The item at the key has been modified.

RELOADED = 4

The item at the key has been reloaded.

REMOVED = 3

The item at the key has been removed.

Developer API

ONDict Object

class resconfig.ondict.ONDict(*args, **kwargs)

Bases: collections.OrderedDict

allkeys(as_str=False)

Generate all keys to the leaves

asdict()

Get a built-in dict representation of itself.

All the nested mappings are converted into dict.

Return type

dict

Returns

Built-in dict object.

clear() → None. Remove all items from od.
copy() → a shallow copy of od
classmethod fromkeys(iterable, value=None)

Create a new ordered dictionary with keys from iterable and values set to value.

get(key, default=None)

Return the value for key if key is in the dictionary, else default.

items() → a set-like object providing a view on D’s items
keys() → a set-like object providing a view on D’s keys
merge(*args, **kwargs)

Merge from dict and/or iterable.

This method takes in the same argument(s) as dict.update(), but merge the input instead of dict-like update. Merging extends the update behavior to allow nested updates and to support nested key notation.

Raises
  • TypeError – When more than one positional argument is supplied.

  • ValueError – When the iterable does not hold two-element items.

move_to_end(key, last=True)

Move an existing element to the end (or beginning if last is false).

Raise KeyError if the element does not exist.

pop(k[, d]) → v, remove specified key and return the corresponding

value. If key is not found, d is returned if given, otherwise KeyError is raised.

popitem(last=True)

Remove and return a (key, value) pair from the dictionary.

Pairs are returned in LIFO order if last is true or FIFO order if false.

setdefault(key, default=None)

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

update(*args, **kwargs)

Update from dict and/or iterable.

This method takes in the same argument(s) as dict.update(). Compared to the built-in dict object, the update behavior is expanded to allow nested key notation.

Note that update happens only on the top-level keys, just like built-in dict, to supply consistent behavior. If you desire a full merging behavior, use ONDict.merge().

Raises
  • TypeError – When more than one positional argument is supplied.

  • ValueError – When the iterable does not hold two-element items.

values() → an object providing a view on D’s values