From: Serhiy Storchaka Date: Wed, 18 Mar 2026 15:04:11 +0000 (+0200) Subject: gh-66419: Make optional arguments with nargs=REMAINDER consume all arguments (GH... X-Git-Tag: v3.15.0a8~266 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=70c7e040d4f50219bd2832391e1a98701281fc58;p=thirdparty%2FPython%2Fcpython.git gh-66419: Make optional arguments with nargs=REMAINDER consume all arguments (GH-124509) It no longer stops at the first '--'. --- diff --git a/Lib/argparse.py b/Lib/argparse.py index 296a210ad832..d91707d9eec5 100644 --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -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: diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py index 4526efe4b80e..e0c32976fd6f 100644 --- a/Lib/test/test_argparse.py +++ b/Lib/test/test_argparse.py @@ -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 index 000000000000..ceac06165994 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2024-09-25-12-47-50.gh-issue-66419.DVSukU.rst @@ -0,0 +1,2 @@ +Optional argument with :ref:`nargs` equals to ``argparse.REMAINDER`` now +consumes all remaining arguments including ``'--'``.