]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-66419: Make optional arguments with nargs=REMAINDER consume all arguments (GH...
authorSerhiy Storchaka <storchaka@gmail.com>
Wed, 18 Mar 2026 15:04:11 +0000 (17:04 +0200)
committerGitHub <noreply@github.com>
Wed, 18 Mar 2026 15:04:11 +0000 (17:04 +0200)
It no longer stops at the first '--'.

Lib/argparse.py
Lib/test/test_argparse.py
Misc/NEWS.d/next/Library/2024-09-25-12-47-50.gh-issue-66419.DVSukU.rst [new file with mode: 0644]

index 296a210ad832da124c6f2ad44d403fdf56640132..d91707d9eec54645c8fdb0346b13363326803ba4 100644 (file)
@@ -2623,7 +2623,7 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
 
         # allow any number of options or arguments
         elif nargs == REMAINDER:
-            nargs_pattern = '([AO]*)' if option else '(.*)'
+            nargs_pattern = '(.*)'
 
         # allow one argument followed by any number of options or arguments
         elif nargs == PARSER:
index 4526efe4b80ef4ab42b4b0b2367d789452056a99..e0c32976fd6f0d1b0433ae76c49bdefb37c6bc90 100644 (file)
@@ -6605,6 +6605,20 @@ class TestDoubleDash(TestCase):
         args = parser.parse_args(['--foo', 'a', '--', 'b', '--', 'c'])
         self.assertEqual(NS(foo='a', bar=['--', 'b', '--', 'c']), args)
 
+    def test_optional_remainder(self):
+        parser = argparse.ArgumentParser(exit_on_error=False)
+        parser.add_argument('--foo', nargs='...')
+        parser.add_argument('bar', nargs='*')
+
+        args = parser.parse_args(['--', '--foo', 'a', 'b'])
+        self.assertEqual(NS(foo=None, bar=['--foo', 'a', 'b']), args)
+        args = parser.parse_args(['--foo', '--', 'a', 'b'])
+        self.assertEqual(NS(foo=['--', 'a', 'b'], bar=[]), args)
+        args = parser.parse_args(['--foo', 'a', '--', 'b'])
+        self.assertEqual(NS(foo=['a', '--', 'b'], bar=[]), args)
+        args = parser.parse_args(['--foo', 'a', 'b', '--'])
+        self.assertEqual(NS(foo=['a', 'b', '--'], bar=[]), args)
+
     def test_subparser(self):
         parser = argparse.ArgumentParser(exit_on_error=False)
         parser.add_argument('foo')
diff --git a/Misc/NEWS.d/next/Library/2024-09-25-12-47-50.gh-issue-66419.DVSukU.rst b/Misc/NEWS.d/next/Library/2024-09-25-12-47-50.gh-issue-66419.DVSukU.rst
new file mode 100644 (file)
index 0000000..ceac061
--- /dev/null
@@ -0,0 +1,2 @@
+Optional argument with :ref:`nargs` equals to ``argparse.REMAINDER`` now
+consumes all remaining arguments including ``'--'``.