Config: allow access/setting config options as with a dict

This commit is contained in:
Benjamin Renard 2022-11-09 10:25:13 +01:00
parent fd2911e810
commit 85d34b7b9a

View file

@ -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')