Skip to content

Commit f36fccb

Browse files
gh-66419: Make optional arguments with nargs=REMAINDER consume all arguments
It no longer stops at the first '--'.
1 parent 0d38409 commit f36fccb

3 files changed

Lines changed: 17 additions & 1 deletion

File tree

Lib/argparse.py

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

23642364
# allow any number of options or arguments
23652365
elif nargs == REMAINDER:
2366-
nargs_pattern = '([-AO]*)'
2366+
nargs_pattern = '(.*)'
23672367

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

Lib/test/test_argparse.py

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

6039+
def test_optional_remainder(self):
6040+
parser = argparse.ArgumentParser(exit_on_error=False)
6041+
parser.add_argument('--foo', nargs='...')
6042+
parser.add_argument('bar', nargs='*')
6043+
6044+
args = parser.parse_args(['--', '--foo', 'a', 'b'])
6045+
self.assertEqual(NS(foo=None, bar=['--foo', 'a', 'b']), args)
6046+
args = parser.parse_args(['--foo', '--', 'a', 'b'])
6047+
self.assertEqual(NS(foo=['--', 'a', 'b'], bar=[]), args)
6048+
args = parser.parse_args(['--foo', 'a', '--', 'b'])
6049+
self.assertEqual(NS(foo=['a', '--', 'b'], bar=[]), args)
6050+
args = parser.parse_args(['--foo', 'a', 'b', '--'])
6051+
self.assertEqual(NS(foo=['a', 'b', '--'], bar=[]), args)
6052+
60396053
def test_subparser(self):
60406054
parser = argparse.ArgumentParser(exit_on_error=False)
60416055
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, not only to the first ``'--'``.

0 commit comments

Comments
 (0)