diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 9aedd8e0..18b805f5 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -19,6 +19,7 @@ Fixed ^^^^^ - Failure to parse subclass added via add_argument and required arg as link target. +- ``choices`` working incorrectly when ``nargs`` is ``+``, ``*`` or number. v4.26.1 (2023-10-23) diff --git a/jsonargparse/_core.py b/jsonargparse/_core.py index da99a6b9..43cc172f 100644 --- a/jsonargparse/_core.py +++ b/jsonargparse/_core.py @@ -1354,8 +1354,12 @@ def _check_value_key(self, action: argparse.Action, value: Any, key: str, cfg: O value[k] = action.type(v) except (TypeError, ValueError) as ex: raise TypeError(f'Parser key "{key}": {ex}') from ex - if not is_subcommand and action.choices and value not in action.choices: - raise TypeError(f'Parser key "{key}": {value!r} not among choices {action.choices}') + if not is_subcommand and action.choices: + vals = value if _is_action_value_list(action) else [value] + assert isinstance(vals, list) + for val in vals: + if val not in action.choices: + raise TypeError(f'Parser key "{key}": {val!r} not among choices {action.choices}') return value ## Properties ## diff --git a/jsonargparse_tests/test_core.py b/jsonargparse_tests/test_core.py index b0d01402..09e340d7 100644 --- a/jsonargparse_tests/test_core.py +++ b/jsonargparse_tests/test_core.py @@ -165,6 +165,14 @@ def test_parse_args_non_hashable_choice(parser): ctx.match("not among choices") +def test_parse_args_choices_nargs_plus(parser): + parser.add_argument("--ch", nargs="+", choices=["A", "B"]) + assert ["A", "B"] == parser.parse_args(["--ch", "A", "B"]).ch + with pytest.raises(ArgumentError) as ctx: + parser.parse_args(["--ch", "B", "X"]) + ctx.match("invalid choice") + + def test_parse_object_simple(parser): parser.add_argument("--op", type=int) assert parser.parse_object({"op": 1}) == Namespace(op=1)