Skip to content

Commit

Permalink
Fix choices working incorrectly when nargs is +, * or number.
Browse files Browse the repository at this point in the history
  • Loading branch information
mauvilsa committed Oct 24, 2023
1 parent 915b047 commit b571fc1
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
8 changes: 6 additions & 2 deletions jsonargparse/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ##
Expand Down
8 changes: 8 additions & 0 deletions jsonargparse_tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit b571fc1

Please sign in to comment.