diff --git a/mylib/config.py b/mylib/config.py index 34e1b08..cb7bfc0 100644 --- a/mylib/config.py +++ b/mylib/config.py @@ -655,6 +655,11 @@ class Config: # pylint: disable=too-many-instance-attributes return getattr(self.options, option) return default + def __getitem__(self, key): + assert self.config_parser or self.options, 'Unconfigured options parser' + assert key in self.sections, f'Unknown section {key}' + return ConfigSectionAsDictWrapper(self.sections[key]) + def set(self, section, option, value): """ Set option value """ assert self.config_parser, 'Unconfigured options parser' @@ -1088,3 +1093,24 @@ class ConfigurableObject: """ Configuration initialized hook """ if loaded_config: self.config = loaded_config # pylint: disable=attribute-defined-outside-init + + +class ConfigSectionAsDictWrapper: + """ + Wrapper for ConfigSection that offer __getitems__ and __setitem__ methods + to allow access to section options as with a dictionary. + """ + + __section = None + + def __init__(self, section): + self.__section = section + + def __getitem__(self, key): + return self.__section.get(key) + + def __setitem__(self, key, value): + self.__section.set(key, value) + + def __delitem__(self, key): + raise Exception('Deleting a configuration option is not supported')