From 9beecbda921a9e920638f57dbd79a285b95c9c32 Mon Sep 17 00:00:00 2001 From: Eric Callahan Date: Fri, 19 Jul 2024 10:25:19 -0400 Subject: [PATCH] confighelper: add getchoice method This getter provides a pattern for configuring an item that within a range of choices. Signed-off-by: Eric Callahan --- moonraker/confighelper.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/moonraker/confighelper.py b/moonraker/confighelper.py index aa802d6..b4dc8fd 100644 --- a/moonraker/confighelper.py +++ b/moonraker/confighelper.py @@ -249,6 +249,31 @@ class ConfigHelper: self.config.getfloat, option, default, above, below, minval, maxval, deprecate) + def getchoice( + self, + option: str, + choices: Union[Dict[str, _T], List[_T]], + default_key: Union[Sentinel, str] = Sentinel.MISSING, + force_lowercase: bool = False, + deprecate: bool = False + ) -> _T: + result: str = self._get_option( + self.config.get, option, default_key, deprecate=deprecate + ) + if force_lowercase: + result = result.lower() + if result not in choices: + items = list(choices.keys()) if isinstance(choices, dict) else choices + raise ConfigError( + f"Section [{self.section}], Option '{option}: Value " + f"{result} is not a vailid choice. Must be one of the " + f"following {items}" + ) + if isinstance(choices, dict): + return choices[result] + else: + return result # type: ignore + def getlists(self, option: str, default: Union[Sentinel, _T] = Sentinel.MISSING,