From b5df95a2dd27a1919514b466706ba68230cd3448 Mon Sep 17 00:00:00 2001 From: Benjamin Renard Date: Mon, 13 Mar 2023 18:53:29 +0100 Subject: [PATCH] Config: add set_default() / set_defaults() methods --- mylib/config.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/mylib/config.py b/mylib/config.py index df0c461..2f8927e 100644 --- a/mylib/config.py +++ b/mylib/config.py @@ -116,6 +116,10 @@ class BaseOption: # pylint: disable=too-many-instance-attributes self._set = True + def set_default(self, default_value): + """Set option default value""" + self.default = default_value + @property def parser_action(self): """Get action as accept by argparse.ArgumentParser""" @@ -511,6 +515,16 @@ class ConfigSection: assert self.defined(option), f"Option {option} unknown" return self.options[option].set(value) + def set_default(self, option, default_value): + """Set default option value""" + assert self.defined(option), f"Option {option} unknown" + return self.options[option].set_default(default_value) + + def set_defaults(self, **default_values): + """Set default options value""" + for option, default_value in default_values.items(): + self.set_default(option, default_value) + def add_options_to_parser(self, parser): """Add section to argparse.ArgumentParser""" assert isinstance(parser, argparse.ArgumentParser) @@ -660,6 +674,18 @@ class Config: # pylint: disable=too-many-instance-attributes self._init_config_parser() self.sections[section].set(option, value) + def set_default(self, section, option, default_value): + """Set default option value""" + assert self.defined(section, option), f"Unknown option {section}.{option}" + self._init_config_parser() + self.sections[section].set_default(option, default_value) + + def set_defaults(self, section, **default_values): + """Set default options value""" + assert section in self.sections, f"Unknown section {section}" + self._init_config_parser() + self.sections[section].set_defaults(**default_values) + def _init_config_parser(self, force=False): """Initialize ConfigParser object""" if not self.config_parser or force: