Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix choices working incorrectly when nargs is +, * or number #410

Merged
merged 1 commit into from
Oct 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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