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
15 changes: 10 additions & 5 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -2470,12 +2470,17 @@ 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 in [ZERO_OR_MORE, ONE_OR_MORE] or
(isinstance(action.nargs, int) and action.nargs > 1)) and
action.type is None):
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
21 changes: 21 additions & 0 deletions Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -5716,6 +5716,27 @@ 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)

parser3 = argparse.ArgumentParser()
parser3.add_argument('foo')
parser3.add_argument('bar', nargs='+')

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

parser4 = argparse.ArgumentParser()
parser4.add_argument('foo')
parser4.add_argument('bar', nargs=3)

args = parser4.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