Skip to content

gh-99749: Suggest closest choice in argparser, if wrong choice is picked #99831

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

Closed
wants to merge 2 commits into from
Closed
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
24 changes: 21 additions & 3 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@
]


import difflib as _difflib
import os as _os
import re as _re
import sys as _sys
Expand Down Expand Up @@ -2541,11 +2542,28 @@ def _get_value(self, action, arg_string):
return result

def _check_value(self, action, value):
if not action.choices and isinstance(action.choices, list):
msg = 'Either add options in choices array or remove it'
raise ArgumentError(action, msg)

# converted value must be one of the choices (if specified)
if action.choices is not None and value not in action.choices:
args = {'value': value,
'choices': ', '.join(map(repr, action.choices))}
msg = _('invalid choice: %(value)r (choose from %(choices)s)')
try:
closest_choice = _difflib.get_close_matches(value, action.choices, 1)
except TypeError:
closest_choice = []

args = {
'value': value,
'choices': ', '.join(map(repr, action.choices)),
}
if closest_choice := closest_choice and closest_choice[0] or None:
args['closest_choice'] = closest_choice
msg = _('invalid choice: %(value)r, maybe you meant'
' %(closest_choice)r? (choose from %(choices)s)')
else:
msg = _('invalid choice: %(value)r (choose from %(choices)s)')

raise ArgumentError(action, msg % args)

# =======================
Expand Down
5 changes: 3 additions & 2 deletions Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -2193,9 +2193,10 @@ def test_wrong_argument_subparsers_no_destination_error(self):
subparsers.add_parser('bar')
with self.assertRaises(ArgumentParserError) as excinfo:
parser.parse_args(('baz',))
self.assertRegex(
self.assertIn(
"error: argument {foo,bar}: invalid choice: 'baz', maybe you meant 'bar'?"
" (choose from 'foo', 'bar')",
excinfo.exception.stderr,
r"error: argument {foo,bar}: invalid choice: 'baz' \(choose from 'foo', 'bar'\)\n$"
)

def test_optional_subparsers(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add closest choice if exists in Argparser if wrong choice picked.