From 85d34b7b9ab24a6527b32e308a600cd3bc2b1ef7 Mon Sep 17 00:00:00 2001 From: Benjamin Renard Date: Wed, 9 Nov 2022 10:25:13 +0100 Subject: [PATCH] Config: allow access/setting config options as with a dict --- mylib/config.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) 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')