Skip to content

Commit 16d43a0

Browse files
serhiy-storchakaebonnal
authored andcommitted
pythongh-117941: Reject option names starting with "--no-" in argparse.BooleanOptionalAction (pythonGH-125894)
They never worked correctly.
1 parent e131426 commit 16d43a0

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
@@ -789,6 +789,13 @@ def test_const(self):
789789

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

792+
def test_invalid_name(self):
793+
parser = argparse.ArgumentParser()
794+
with self.assertRaises(ValueError) as cm:
795+
parser.add_argument('--no-foo', action=argparse.BooleanOptionalAction)
796+
self.assertEqual(str(cm.exception),
797+
"invalid option name '--no-foo' for BooleanOptionalAction")
798+
792799
class TestBooleanOptionalActionRequired(ParserTestCase):
793800
"""Tests BooleanOptionalAction required"""
794801

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)