Skip to content

Commit 70c7e04

Browse files
gh-66419: Make optional arguments with nargs=REMAINDER consume all arguments (GH-124509)
It no longer stops at the first '--'.
1 parent 847f83e commit 70c7e04

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

Lib/argparse.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2623,7 +2623,7 @@ def _get_nargs_pattern(self, action):
26232623

26242624
# allow any number of options or arguments
26252625
elif nargs == REMAINDER:
2626-
nargs_pattern = '([AO]*)' if option else '(.*)'
2626+
nargs_pattern = '(.*)'
26272627

26282628
# allow one argument followed by any number of options or arguments
26292629
elif nargs == PARSER:

Lib/test/test_argparse.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6605,6 +6605,20 @@ def test_remainder(self):
66056605
args = parser.parse_args(['--foo', 'a', '--', 'b', '--', 'c'])
66066606
self.assertEqual(NS(foo='a', bar=['--', 'b', '--', 'c']), args)
66076607

6608+
def test_optional_remainder(self):
6609+
parser = argparse.ArgumentParser(exit_on_error=False)
6610+
parser.add_argument('--foo', nargs='...')
6611+
parser.add_argument('bar', nargs='*')
6612+
6613+
args = parser.parse_args(['--', '--foo', 'a', 'b'])
6614+
self.assertEqual(NS(foo=None, bar=['--foo', 'a', 'b']), args)
6615+
args = parser.parse_args(['--foo', '--', 'a', 'b'])
6616+
self.assertEqual(NS(foo=['--', 'a', 'b'], bar=[]), args)
6617+
args = parser.parse_args(['--foo', 'a', '--', 'b'])
6618+
self.assertEqual(NS(foo=['a', '--', 'b'], bar=[]), args)
6619+
args = parser.parse_args(['--foo', 'a', 'b', '--'])
6620+
self.assertEqual(NS(foo=['a', 'b', '--'], bar=[]), args)
6621+
66086622
def test_subparser(self):
66096623
parser = argparse.ArgumentParser(exit_on_error=False)
66106624
parser.add_argument('foo')
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Optional argument with :ref:`nargs` equals to ``argparse.REMAINDER`` now
2+
consumes all remaining arguments including ``'--'``.

0 commit comments

Comments
 (0)