]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-109475: Fix support of explicit option value "--" in argparse (GH-114814)
authorSerhiy Storchaka <storchaka@gmail.com>
Mon, 5 Feb 2024 20:42:43 +0000 (22:42 +0200)
committerGitHub <noreply@github.com>
Mon, 5 Feb 2024 20:42:43 +0000 (22:42 +0200)
For example "--option=--".

Lib/argparse.py
Lib/test/test_argparse.py
Misc/NEWS.d/next/Library/2024-01-31-20-07-11.gh-issue-109475.lmTb9S.rst [new file with mode: 0644]

index 9e19f39fadd87bcd9499fae965bb78b58045bcd9..2131d729746d41ee9b9927e0c028978dbcaf52ba 100644 (file)
@@ -2485,7 +2485,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:
index 940d7e95f96e20a865d64e8a915f6cd0b001ee47..d1f3d40000140d3e738d84c69a3ff5411ddd4568 100644 (file)
@@ -5405,6 +5405,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 (file)
index 0000000..7582cb2
--- /dev/null
@@ -0,0 +1,2 @@
+Fix support of explicit option value "--" in :mod:`argparse` (e.g.
+``--option=--``).