Skip to content

Commit 0e838b5

Browse files
[3.12] gh-53780: Ignore the first "--" (double dash) between an option and command in argparse (GH-124275) (GH-124420)
(cherry picked from commit c578271) Co-authored-by: Serhiy Storchaka <[email protected]>
1 parent e57fbe3 commit 0e838b5

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
@@ -2106,11 +2106,15 @@ def consume_positionals(start_index):
21062106
# and add the Positional and its args to the list
21072107
for action, arg_count in zip(positionals, arg_counts):
21082108
args = arg_strings[start_index: start_index + arg_count]
2109-
# Strip out the first '--' if it is not in PARSER or REMAINDER arg.
2110-
if (action.nargs not in [PARSER, REMAINDER]
2111-
and arg_strings_pattern.find('-', start_index,
2109+
# Strip out the first '--' if it is not in REMAINDER arg.
2110+
if action.nargs == PARSER:
2111+
if arg_strings_pattern[start_index] == '-':
2112+
assert args[0] == '--'
2113+
args.remove('--')
2114+
elif action.nargs != REMAINDER:
2115+
if (arg_strings_pattern.find('-', start_index,
21122116
start_index + arg_count) >= 0):
2113-
args.remove('--')
2117+
args.remove('--')
21142118
start_index += arg_count
21152119
take_action(action, args)
21162120

Lib/test/test_argparse.py

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

5648+
def test_subparser_after_multiple_argument_option(self):
5649+
parser = argparse.ArgumentParser(exit_on_error=False)
5650+
parser.add_argument('--foo', nargs='*')
5651+
subparsers = parser.add_subparsers()
5652+
parser1 = subparsers.add_parser('run')
5653+
parser1.add_argument('-f')
5654+
parser1.add_argument('bar', nargs='*')
5655+
5656+
args = parser.parse_args(['--foo', 'x', 'y', '--', 'run', 'a', 'b', '-f', 'c'])
5657+
self.assertEqual(NS(foo=['x', 'y'], f='c', bar=['a', 'b']), args)
5658+
self.assertRaisesRegex(argparse.ArgumentError,
5659+
"invalid choice: '--'",
5660+
parser.parse_args, ['--foo', 'x', '--', '--', 'run', 'a', 'b'])
5661+
56485662

56495663
# ===========================
56505664
# 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)