diff --git a/Lib/argparse.py b/Lib/argparse.py index 690b2a9db9481b..6b99be80591ec4 100644 --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -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 diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py index ef05a6fefcffcc..efa0fd764dd0af 100644 --- a/Lib/test/test_argparse.py +++ b/Lib/test/test_argparse.py @@ -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() diff --git a/Misc/NEWS.d/next/Library/2020-07-06-15-25-29.bpo-22433.JBnwdX.rst b/Misc/NEWS.d/next/Library/2020-07-06-15-25-29.bpo-22433.JBnwdX.rst new file mode 100644 index 00000000000000..aa0adb5a732987 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2020-07-06-15-25-29.bpo-22433.JBnwdX.rst @@ -0,0 +1,2 @@ +Fixed handling of "--foo='bar baz'" as non-positional argument with +:mod:`argparse`.