Skip to content

Commit

Permalink
pythongh-117941: Reject option names starting with "--no-" in argpars…
Browse files Browse the repository at this point in the history
…e.BooleanOptionalAction

They never worked correctly.
  • Loading branch information
serhiy-storchaka committed Oct 23, 2024
1 parent 6f26d49 commit 51bbf5e
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 0 deletions.
3 changes: 3 additions & 0 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -863,6 +863,9 @@ def __init__(self,
_option_strings.append(option_string)

if option_string.startswith('--'):
if option_string.startswith('--no-'):
raise ValueError(f'invalid option name {option_string} '
f'for BooleanOptionalAction')
option_string = '--no-' + option_string[2:]
_option_strings.append(option_string)

Expand Down
7 changes: 7 additions & 0 deletions Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -782,6 +782,13 @@ def test_const(self):

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"""

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

0 comments on commit 51bbf5e

Please sign in to comment.