From f36fccb22c4e1fe25fe20694c3c0c1cf26581010 Mon Sep 17 00:00:00 2001 From: Serhiy Storchaka Date: Wed, 25 Sep 2024 12:47:54 +0300 Subject: [PATCH] gh-66419: Make optional arguments with nargs=REMAINDER consume all arguments It no longer stops at the first '--'. --- Lib/argparse.py | 2 +- Lib/test/test_argparse.py | 14 ++++++++++++++ .../2024-09-25-12-47-50.gh-issue-66419.DVSukU.rst | 2 ++ 3 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2024-09-25-12-47-50.gh-issue-66419.DVSukU.rst diff --git a/Lib/argparse.py b/Lib/argparse.py index 690b2a9db9481b..ef825cdef92a37 100644 --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -2363,7 +2363,7 @@ def _get_nargs_pattern(self, action): # allow any number of options or arguments elif nargs == REMAINDER: - nargs_pattern = '([-AO]*)' + 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 ef05a6fefcffcc..be6a907f47b5bd 100644 --- a/Lib/test/test_argparse.py +++ b/Lib/test/test_argparse.py @@ -6036,6 +6036,20 @@ def test_remainder(self): 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 00000000000000..45da08bde7c311 --- /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, not only to the first ``'--'``.