]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-125254: Fix error report about ambiguous option in argparse (GH-125273)
authorSerhiy Storchaka <storchaka@gmail.com>
Sat, 12 Oct 2024 12:15:37 +0000 (15:15 +0300)
committerGitHub <noreply@github.com>
Sat, 12 Oct 2024 12:15:37 +0000 (12:15 +0000)
This was a regression introduced in gh-58573. It was only tested for the
case when the ambiguous option is the last argument in the command line.

Lib/argparse.py
Lib/test/test_argparse.py
Misc/NEWS.d/next/Library/2024-10-10-19-57-35.gh-issue-125254.RtZxXS.rst [new file with mode: 0644]

index 64dbd7149e769c2c3dd0efcd54fe0ecdc5ff6e1b..cbecb3b753c2b9cfd217d0107c5253016291e4eb 100644 (file)
@@ -2019,7 +2019,7 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
             if len(option_tuples) > 1:
                 options = ', '.join([option_string
                     for action, option_string, sep, explicit_arg in option_tuples])
-                args = {'option': arg_string, 'matches': options}
+                args = {'option': arg_strings[start_index], 'matches': options}
                 msg = _('ambiguous option: %(option)s could match %(matches)s')
                 raise ArgumentError(None, msg % args)
 
index 61ddb5f16cc44f36c48ecb657bcbd7fda9ac9e18..1fc97de78f7f895add34a29340796cdbfe36d619 100644 (file)
@@ -6730,9 +6730,19 @@ class TestExitOnError(TestCase):
     def test_ambiguous_option(self):
         self.parser.add_argument('--foobaz')
         self.parser.add_argument('--fooble', action='store_true')
+        self.parser.add_argument('--foogle')
         self.assertRaisesRegex(argparse.ArgumentError,
-                               "ambiguous option: --foob could match --foobaz, --fooble",
-                               self.parser.parse_args, ['--foob'])
+                "ambiguous option: --foob could match --foobaz, --fooble",
+            self.parser.parse_args, ['--foob'])
+        self.assertRaisesRegex(argparse.ArgumentError,
+                "ambiguous option: --foob=1 could match --foobaz, --fooble$",
+            self.parser.parse_args, ['--foob=1'])
+        self.assertRaisesRegex(argparse.ArgumentError,
+                "ambiguous option: --foob could match --foobaz, --fooble$",
+            self.parser.parse_args, ['--foob', '1', '--foogle', '2'])
+        self.assertRaisesRegex(argparse.ArgumentError,
+                "ambiguous option: --foob=1 could match --foobaz, --fooble$",
+            self.parser.parse_args, ['--foob=1', '--foogle', '2'])
 
     def test_os_error(self):
         self.parser.add_argument('file')
diff --git a/Misc/NEWS.d/next/Library/2024-10-10-19-57-35.gh-issue-125254.RtZxXS.rst b/Misc/NEWS.d/next/Library/2024-10-10-19-57-35.gh-issue-125254.RtZxXS.rst
new file mode 100644 (file)
index 0000000..abe37fe
--- /dev/null
@@ -0,0 +1 @@
+Fix a bug where ArgumentError includes the incorrect ambiguous option in :mod:`argparse`.