Skip to content

Commit

Permalink
pythongh-66419: Make optional arguments with nargs=REMAINDER consume …
Browse files Browse the repository at this point in the history
…all arguments

It no longer stops at the first '--'.
  • Loading branch information
serhiy-storchaka committed Sep 25, 2024
1 parent 0d38409 commit f36fccb
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
14 changes: 14 additions & 0 deletions Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Optional argument with :ref:`nargs` equals to ``argparse.REMAINDER`` now
consumes all remaining arguments, not only to the first ``'--'``.

0 comments on commit f36fccb

Please sign in to comment.