]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-92445 Improve interaction between nargs="*" and choices() (GH-92565)
authorHarry <harry.lees@gmail.com>
Thu, 25 Aug 2022 11:18:38 +0000 (12:18 +0100)
committerGitHub <noreply@github.com>
Thu, 25 Aug 2022 11:18:38 +0000 (06:18 -0500)
Lib/argparse.py
Lib/test/test_argparse.py
Misc/NEWS.d/next/Library/2022-05-09-21-31-41.gh-issue-92445.tJosdm.rst [new file with mode: 0644]

index 02e98bbf920cf1dcc0d05c57cce1336efb17f465..fe48f8670fa20a48699e1f20d58a75e5784253b7 100644 (file)
@@ -2477,9 +2477,11 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
               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]:
index 425b6bb3e0b4ee6a7aeafaff823a5728f25049cb..2b7f008d38564bcfccd2af98c31a3b7d072b969e 100644 (file)
@@ -5230,6 +5230,13 @@ class TestParseKnownArgs(TestCase):
         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 (file)
index 0000000..ba69a01
--- /dev/null
@@ -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``.