]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-117941: Reject option names starting with "--no-" in argparse.BooleanOptionalActio...
authorSerhiy Storchaka <storchaka@gmail.com>
Mon, 11 Nov 2024 16:28:30 +0000 (18:28 +0200)
committerGitHub <noreply@github.com>
Mon, 11 Nov 2024 16:28:30 +0000 (18:28 +0200)
They never worked correctly.

Lib/argparse.py
Lib/test/test_argparse.py
Misc/NEWS.d/next/Library/2024-10-23-20-44-30.gh-issue-117941.Y9jdlW.rst [new file with mode: 0644]

index 072cd5e7dc0d06e6e15b9da0b0b2b3fa223dd439..5ecfdca17175e387e060491f0a2571e48137ec25 100644 (file)
@@ -863,6 +863,9 @@ class BooleanOptionalAction(Action):
             _option_strings.append(option_string)
 
             if option_string.startswith('--'):
+                if option_string.startswith('--no-'):
+                    raise ValueError(f'invalid option name {option_string!r} '
+                                     f'for BooleanOptionalAction')
                 option_string = '--no-' + option_string[2:]
                 _option_strings.append(option_string)
 
index ba9876570385d358f5ec186d0d27adf995c042da..cbf119ed2dabbb79f5815d1e84ec01c38439345b 100644 (file)
@@ -789,6 +789,13 @@ class TestBooleanOptionalAction(ParserTestCase):
 
         self.assertIn("got an unexpected keyword argument 'const'", str(cm.exception))
 
+    def test_invalid_name(self):
+        parser = argparse.ArgumentParser()
+        with self.assertRaises(ValueError) as cm:
+            parser.add_argument('--no-foo', action=argparse.BooleanOptionalAction)
+        self.assertEqual(str(cm.exception),
+                         "invalid option name '--no-foo' for BooleanOptionalAction")
+
 class TestBooleanOptionalActionRequired(ParserTestCase):
     """Tests BooleanOptionalAction required"""
 
diff --git a/Misc/NEWS.d/next/Library/2024-10-23-20-44-30.gh-issue-117941.Y9jdlW.rst b/Misc/NEWS.d/next/Library/2024-10-23-20-44-30.gh-issue-117941.Y9jdlW.rst
new file mode 100644 (file)
index 0000000..9c2553f
--- /dev/null
@@ -0,0 +1,2 @@
+:class:`!argparse.BooleanOptionalAction` now rejects option names starting
+with ``--no-``.