Skip to content

Commit

Permalink
fixes parse bool type
Browse files Browse the repository at this point in the history
Signed-off-by: Zhiyuan Chen <[email protected]>
  • Loading branch information
ZhiyuanChen committed Sep 19, 2023
1 parent 272763d commit 4861781
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
11 changes: 7 additions & 4 deletions chanfig/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)

Expand Down
11 changes: 11 additions & 0 deletions chanfig/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.")

0 comments on commit 4861781

Please sign in to comment.