Skip to content

Commit 714c456

Browse files
gh-117941: Reject option names starting with "--no-" in argparse.BooleanOptionalAction
They never worked correctly.
1 parent 6f26d49 commit 714c456

File tree

3 files changed

+12
-0
lines changed

3 files changed

+12
-0
lines changed

Lib/argparse.py

+3
Original file line numberDiff line numberDiff line change
@@ -863,6 +863,9 @@ def __init__(self,
863863
_option_strings.append(option_string)
864864

865865
if option_string.startswith('--'):
866+
if option_string.startswith('--no-'):
867+
raise ValueError(f'invalid option name {option_string!r} '
868+
f'for BooleanOptionalAction')
866869
option_string = '--no-' + option_string[2:]
867870
_option_strings.append(option_string)
868871

Lib/test/test_argparse.py

+7
Original file line numberDiff line numberDiff line change
@@ -782,6 +782,13 @@ def test_const(self):
782782

783783
self.assertIn("got an unexpected keyword argument 'const'", str(cm.exception))
784784

785+
def test_invalid_name(self):
786+
parser = argparse.ArgumentParser()
787+
with self.assertRaises(ValueError) as cm:
788+
parser.add_argument('--no-foo', action=argparse.BooleanOptionalAction)
789+
self.assertEqual(str(cm.exception),
790+
"invalid option name '--no-foo' for BooleanOptionalAction")
791+
785792
class TestBooleanOptionalActionRequired(ParserTestCase):
786793
"""Tests BooleanOptionalAction required"""
787794

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
:class:`argparse.BooleanOptionalAction` now rejects option names starting
2+
with ``--no-``.

0 commit comments

Comments
 (0)