diff --git a/chanfig/parser.py b/chanfig/parser.py index 33db9037..28067636 100644 --- a/chanfig/parser.py +++ b/chanfig/parser.py @@ -24,7 +24,7 @@ from warnings import warn from .nested_dict import NestedDict -from .utils import Null +from .utils import Null, parse_bool from .variable import Variable if TYPE_CHECKING: @@ -62,9 +62,10 @@ def parse_args( # type: ignore if not isinstance(parsed, NestedDict): parsed = NestedDict({key: value for key, value in parsed.items() if value is not Null}) # type: ignore for key, value in parsed.all_items(): - with suppress(TypeError, ValueError, SyntaxError): - value = literal_eval(value) - parsed[key] = value + if isinstance(value, str): + with suppress(TypeError, ValueError, SyntaxError): + value = literal_eval(value) + parsed[key] = value return parsed # type: ignore def parse( # pylint: disable=R0912 @@ -268,6 +269,8 @@ def add_config_arguments(self, config): help = value._help if isinstance(value, Variable) else None # pylint: disable=W0212,W0622 if isinstance(value, (list, tuple, dict, set)): self.add_argument(name, type=dtype, nargs="+", help=help, dest=key) + elif isinstance(value, bool): + self.add_argument(name, type=parse_bool, help=help, dest=key) else: self.add_argument(name, type=dtype, help=help, dest=key) diff --git a/chanfig/utils.py b/chanfig/utils.py index 6127d93f..78533001 100644 --- a/chanfig/utils.py +++ b/chanfig/utils.py @@ -16,6 +16,7 @@ from __future__ import annotations import sys +from argparse import ArgumentTypeError from collections.abc import Callable, Mapping, Sequence from functools import partial from io import IOBase @@ -333,3 +334,13 @@ def dfs(node, visited, path): return result return None + + +def parse_bool(value): + if isinstance(value, bool): + return value + if value.lower() in ("yes", "true", "t", "y", "1"): + return True + if value.lower() in ("no", "false", "f", "n", "0"): + return False + raise ArgumentTypeError("Boolean value expected.")