Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-117941: Reject option names starting with "--no-" in argparse.BooleanOptionalAction #125894

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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!r} '
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 @@ -789,6 +789,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-``.
Loading