gh-92445 Improve interaction between nargs="*" and choices() (GH-92565)

https://github.com/python/cpython/commit/ad7340e8c56f61edc1ff4724fe32c9d831d... commit: ad7340e8c56f61edc1ff4724fe32c9d831db51a7 branch: main author: Harry <harry.lees@gmail.com> committer: rhettinger <rhettinger@users.noreply.github.com> date: 2022-08-25T06:18:38-05:00 summary: gh-92445 Improve interaction between nargs="*" and choices() (GH-92565) files: A Misc/NEWS.d/next/Library/2022-05-09-21-31-41.gh-issue-92445.tJosdm.rst M Lib/argparse.py M Lib/test/test_argparse.py diff --git a/Lib/argparse.py b/Lib/argparse.py index 02e98bbf920c..fe48f8670fa2 100644 --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -2477,9 +2477,11 @@ def _get_values(self, action, arg_strings): not action.option_strings): if action.default is not None: value = action.default + self._check_value(action, value) else: + # since arg_strings is always [] at this point + # there is no need to use self._check_value(action, value) value = arg_strings - self._check_value(action, value) # single argument or optional argument produces a single value elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]: diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py index 425b6bb3e0b4..2b7f008d3856 100644 --- a/Lib/test/test_argparse.py +++ b/Lib/test/test_argparse.py @@ -5230,6 +5230,13 @@ def test_mixed(self): self.assertEqual(NS(v=3, spam=True, badger="B"), args) self.assertEqual(["C", "--foo", "4"], extras) + def test_zero_or_more_optional(self): + parser = argparse.ArgumentParser() + parser.add_argument('x', nargs='*', choices=('x', 'y')) + args = parser.parse_args([]) + self.assertEqual(NS(x=[]), args) + + # =========================== # parse_intermixed_args tests # =========================== diff --git a/Misc/NEWS.d/next/Library/2022-05-09-21-31-41.gh-issue-92445.tJosdm.rst b/Misc/NEWS.d/next/Library/2022-05-09-21-31-41.gh-issue-92445.tJosdm.rst new file mode 100644 index 000000000000..ba69a011601f --- /dev/null +++ b/Misc/NEWS.d/next/Library/2022-05-09-21-31-41.gh-issue-92445.tJosdm.rst @@ -0,0 +1,3 @@ +Fix a bug in :mod:`argparse` where `nargs="*"` would raise an error instead of returning +an empty list when 0 arguments were supplied if choice was also defined in +``parser.add_argument``.
participants (1)
-
rhettinger