From 79805d228440814c0674ab5190ef17f235503d2e Mon Sep 17 00:00:00 2001 From: Serhiy Storchaka Date: Mon, 11 Nov 2024 18:28:30 +0200 Subject: [PATCH] gh-117941: Reject option names starting with "--no-" in argparse.BooleanOptionalAction (GH-125894) They never worked correctly. --- Lib/argparse.py | 3 +++ Lib/test/test_argparse.py | 7 +++++++ .../Library/2024-10-23-20-44-30.gh-issue-117941.Y9jdlW.rst | 2 ++ 3 files changed, 12 insertions(+) create mode 100644 Misc/NEWS.d/next/Library/2024-10-23-20-44-30.gh-issue-117941.Y9jdlW.rst diff --git a/Lib/argparse.py b/Lib/argparse.py index 072cd5e7dc0..5ecfdca1717 100644 --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -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) diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py index ba987657038..cbf119ed2da 100644 --- a/Lib/test/test_argparse.py +++ b/Lib/test/test_argparse.py @@ -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 index 00000000000..9c2553f0f0e --- /dev/null +++ b/Misc/NEWS.d/next/Library/2024-10-23-20-44-30.gh-issue-117941.Y9jdlW.rst @@ -0,0 +1,2 @@ +:class:`!argparse.BooleanOptionalAction` now rejects option names starting +with ``--no-``.