Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit db3ccd8

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

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
@@ -2097,11 +2097,15 @@ def consume_positionals(start_index):
20972097
# and add the Positional and its args to the list
20982098
for action, arg_count in zip(positionals, arg_counts):
20992099
args = arg_strings[start_index: start_index + arg_count]
2100-
# Strip out the first '--' if it is not in PARSER or REMAINDER arg.
2101-
if (action.nargs not in [PARSER, REMAINDER]
2102-
and arg_strings_pattern.find('-', start_index,
2100+
# Strip out the first '--' if it is not in REMAINDER arg.
2101+
if action.nargs == PARSER:
2102+
if arg_strings_pattern[start_index] == '-':
2103+
assert args[0] == '--'
2104+
args.remove('--')
2105+
elif action.nargs != REMAINDER:
2106+
if (arg_strings_pattern.find('-', start_index,
21032107
start_index + arg_count) >= 0):
2104-
args.remove('--')
2108+
args.remove('--')
21052109
start_index += arg_count
21062110
if args and action.deprecated and action.dest not in warned:
21072111
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
@@ -6106,6 +6106,20 @@ def test_subparser(self):
61066106
"invalid choice: '--'",
61076107
parser.parse_args, ['--', 'x', '--', 'run', 'a', 'b'])
61086108

6109+
def test_subparser_after_multiple_argument_option(self):
6110+
parser = argparse.ArgumentParser(exit_on_error=False)
6111+
parser.add_argument('--foo', nargs='*')
6112+
subparsers = parser.add_subparsers()
6113+
parser1 = subparsers.add_parser('run')
6114+
parser1.add_argument('-f')
6115+
parser1.add_argument('bar', nargs='*')
6116+
6117+
args = parser.parse_args(['--foo', 'x', 'y', '--', 'run', 'a', 'b', '-f', 'c'])
6118+
self.assertEqual(NS(foo=['x', 'y'], f='c', bar=['a', 'b']), args)
6119+
self.assertRaisesRegex(argparse.ArgumentError,
6120+
"invalid choice: '--'",
6121+
parser.parse_args, ['--foo', 'x', '--', '--', 'run', 'a', 'b'])
6122+
61096123

61106124
# ===========================
61116125
# 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)