Skip to content

bpo-22433: do not consider "--foo='bar baz'" to be a positional argument #20924

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
5 changes: 3 additions & 2 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -2290,8 +2290,9 @@ def _parse_optional(self, arg_string):
if not self._has_negative_number_optionals:
return None

# if it contains a space, it was meant to be a positional
if ' ' in arg_string:
# if it contains a space (before any equal sign), it was meant to be a
# positional
if ' ' in arg_string.split("=", 1)[0]:
return None

# it was meant to be an optional but there is no such option
Expand Down
9 changes: 9 additions & 0 deletions Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -2311,6 +2311,15 @@ def test_parse_known_args(self):
self.parser.parse_known_args('0.5 -W 1 b -X Y -w 7 Z'.split()),
(NS(foo=False, bar=0.5, w=7, x='b'), ['-W', '-X', 'Y', 'Z']),
)
self.assertEqual(
self.parser.parse_known_args(['0.5', '--opt="with space"']),
(NS(foo=False, bar=0.5), ['--opt="with space"']),
)
self.assertRaisesRegex(
ArgumentParserError,
"invalid choice: '--opt with space'",
self.parser.parse_known_args,
['0.5', '--opt with space'])

def test_parse_known_args_with_single_dash_option(self):
parser = ErrorRaisingArgumentParser()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fixed handling of "--foo='bar baz'" as non-positional argument with
:mod:`argparse`.
Loading