8000 gh-53780: Ignore the first "--" (double dash) between an option and c… · python/cpython@c578271 · GitHub
[go: up one dir, main page]

Skip to content

Commit c578271

Browse files
gh-53780: Ignore the first "--" (double dash) between an option and command in argparse (GH-124275)
1 parent 3094cd1 commit c578271

File tree

3 files changed

+23
-4
lines changed

3 files changed

+23
-4
lines changed

Lib/argparse.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2068,11 +2068,15 @@ def consume_positionals(start_index):
20682068
# and add the Positional and its args to the list
20692069
for action, arg_count in zip(positionals, arg_counts):
20702070
args = arg_strings[start_index: start_index + arg_count]
2071-
# Strip out the first '--' if it is not in PARSER or REMAINDER arg.
2072-
if (action.nargs not in [PARSER, REMAINDER]
2073-
and arg_strings_pattern.find('-', start_index,
2071+
# Strip out the first '--' if it is not in REMAINDER arg.
2072+
if action.nargs == PARSER:
2073+
if arg_strings_pattern[start_index] == '-':
2074+
assert args[0] == '--'
2075+
args.remove('--')
2076+
elif action.nargs != REMAINDER:
2077+
if (arg_strings_pattern.find('-', start_index,
20742078
start_index + arg_count) >= 0):
2075-
args.remove('--')
2079+
args.remove('--')
20762080
start_index += arg_count
20772081
if args and action.deprecated and action.dest not in warned:
20782082
self._warning(_("argument '%(argument_name)s' is deprecated") %

Lib/test/test_argparse.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5984,6 +5984,20 @@ def test_subparser(self):
59845984
"invalid choice: '--'",
59855985
parser.parse_args, ['--', 'x', '--', 'run', 'a', 'b'])
59865986

5987+
def test_subparser_after_multiple_argument_option(self):
5988+
parser = argparse.ArgumentParser(exit_on_error=False)
5989+
parser.add_argument('--foo', nargs='*')
5990+
subparsers = parser.add_subparsers()
5991+
parser1 = subparsers.add_parser('run')
5992+
parser1.add_argument('-f')
5993+
parser1.add_argument('bar', nargs='*')
5994+
5995+
args = parser.parse_args(['--foo', 'x', 'y', '--', 'run', 'a', 'b', '-f', 'c'])
5996+
self.assertEqual(NS(foo=['x', 'y'], f='c', bar=['a', 'b']), args)
5997+
self.assertRaisesRegex(argparse.ArgumentError,
5998+
"invalid choice: '--'",
5999+
parser.parse_args, ['--foo', 'x', '--', '--', 'run', 'a', 'b'])
6000+
59876001

59886002
# ===========================
59896003
# parse_intermixed_args tests
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
:mod:`argparse` now ignores the first ``"--"`` (double dash) between an option and command.

0 commit comments

Comments
 (0)
0