From: Miss Islington (bot) <31488909+miss-islington@users.noreply.github.com> Date: Mon, 5 Feb 2024 21:02:00 +0000 (+0100) Subject: [3.12] gh-109475: Fix support of explicit option value "--" in argparse (GH-114814... X-Git-Tag: v3.12.2~12 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=94ad68264c5d1651b601787fe10a379afe6ee18b;p=thirdparty%2FPython%2Fcpython.git [3.12] gh-109475: Fix support of explicit option value "--" in argparse (GH-114814) (GH-115036) For example "--option=--". (cherry picked from commit 4aa4f0906df9fc9c6c6f6657f2c521468c6b1688) Co-authored-by: Serhiy Storchaka --- diff --git a/Lib/argparse.py b/Lib/argparse.py index 543d9944f9ed..484a1efde43c 100644 --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -2488,7 +2488,7 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): # ======================== def _get_values(self, action, arg_strings): # for everything but PARSER, REMAINDER args, strip out first '--' - if action.nargs not in [PARSER, REMAINDER]: + if not action.option_strings and action.nargs not in [PARSER, REMAINDER]: try: arg_strings.remove('--') except ValueError: diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py index 3a62a16cee31..88cc62a4cd39 100644 --- a/Lib/test/test_argparse.py +++ b/Lib/test/test_argparse.py @@ -5332,6 +5332,22 @@ class TestParseKnownArgs(TestCase): args = parser.parse_args([]) self.assertEqual(NS(x=[]), args) + def test_double_dash(self): + parser = argparse.ArgumentParser() + parser.add_argument('-f', '--foo', nargs='*') + parser.add_argument('bar', nargs='*') + + args = parser.parse_args(['--foo=--']) + self.assertEqual(NS(foo=['--'], bar=[]), args) + args = parser.parse_args(['--foo', '--']) + self.assertEqual(NS(foo=[], bar=[]), args) + args = parser.parse_args(['-f--']) + self.assertEqual(NS(foo=['--'], bar=[]), args) + args = parser.parse_args(['-f', '--']) + self.assertEqual(NS(foo=[], bar=[]), args) + args = parser.parse_args(['--foo', 'a', 'b', '--', 'c', 'd']) + self.assertEqual(NS(foo=['a', 'b'], bar=['c', 'd']), args) + # =========================== # parse_intermixed_args tests diff --git a/Misc/NEWS.d/next/Library/2024-01-31-20-07-11.gh-issue-109475.lmTb9S.rst b/Misc/NEWS.d/next/Library/2024-01-31-20-07-11.gh-issue-109475.lmTb9S.rst new file mode 100644 index 000000000000..7582cb2bcd76 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2024-01-31-20-07-11.gh-issue-109475.lmTb9S.rst @@ -0,0 +1,2 @@ +Fix support of explicit option value "--" in :mod:`argparse` (e.g. +``--option=--``).