Skip to content

GH-95468: Prevent argparse from removing -- in cases where used to delineate positional args #124145

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 13 commits into from
Closed
16 changes: 11 additions & 5 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -2470,12 +2470,18 @@ def parse_known_intermixed_args(self, args=None, namespace=None):
# Value conversion methods
# ========================
def _get_values(self, action, arg_strings):
# for everything but PARSER, REMAINDER args, strip out first '--'
if not action.option_strings and action.nargs not in [PARSER, REMAINDER]:
try:
arg_strings.remove('--')
except ValueError:
pass
if action.nargs == ZERO_OR_MORE and action.type is None:
# if nargs='*' starts with '--', then we should treat any
# subsequent arguments as positional arguments and we should not
# strip out the first '--' unless it violates the specified nargs type
if arg_strings and arg_strings[0] == '--':
arg_strings = arg_strings[1:]
else:
try:
arg_strings.remove('--')
except ValueError:
pass

# optional argument produces a default when not present
if not arg_strings and action.nargs == OPTIONAL:
Expand Down
6 changes: 6 additions & 0 deletions Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -5716,6 +5716,12 @@ def test_double_dash(self):
args = parser.parse_args(['--foo', 'a', 'b', '--', 'c', 'd'])
self.assertEqual(NS(foo=['a', 'b'], bar=['c', 'd']), args)

parser2 = argparse.ArgumentParser()
parser2.add_argument('foo')
parser2.add_argument('bar', nargs='*')

args = parser2.parse_args(['foo', '--', '--bar', '--', 'com'])
self.assertEqual(NS(foo='foo', bar=['--bar', '--', 'com']), args)

# ===========================
# parse_intermixed_args tests
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix a bug where :mod:`argparse` would remove "--" in cases where it delineates positional arguments in nargs.
Loading