Skip to content

gh-99749: Add closest choice if exists in Argparser if wrong choice picked #99773

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 24 commits into from
Closed
Show file tree
Hide file tree
Changes from 21 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
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
17 changes: 13 additions & 4 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@
'ZERO_OR_MORE',
]


import difflib as _difflib
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we'd probably want to move the import down into the case where the error is thrown, since this is probably not going to be used very often.

import os as _os
import re as _re
import sys as _sys
Expand Down Expand Up @@ -2543,9 +2543,18 @@ def _get_value(self, action, arg_string):
def _check_value(self, action, value):
# 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)')
closest_choice = _difflib.get_close_matches(value, action.choices)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this might fail if action.choices are not strings

Copy link
Author

@abdulrafey38 abdulrafey38 Nov 26, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

argparser does not accept choices other than string, it will throw error even before reaching at this line
reference ==> https://stackoverflow.com/questions/49578928/typeerror-int-object-is-not-subscriptable-when-i-try-to-pass-three-arguments

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The second example for the documentation (https://docs.python.org/3/library/argparse.html#choices)

parser = argparse.ArgumentParser(prog='doors.py')
parser.add_argument('door', type=int, choices=range(1, 4))
print(parser.parse_args(['3']))

Also - I would use

Suggested change
closest_choice = _difflib.get_close_matches(value, action.choices)
closest_choice = _difflib.get_close_matches(value, action.choices, 1)

args = {
'value': value,
'choices': ', '.join(map(repr, action.choices)),
}
if closest_choice := closest_choice and closest_choice[0] or None:
args['closest'] = closest_choice
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if closest_choice := closest_choice and closest_choice[0] or None:
args['closest'] = closest_choice
if closest_choice:
args['closest'] = closest_choice[0]

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why not the above one liner?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the one liner is less readable - at least to me

msg = _('invalid choice: %(value)r, maybe you meant %(closest)r? '
'(choose from %(choices)s)')
else:
msg = _('invalid choice: %(value)r (choose from %(choices)s)')

raise ArgumentError(action, msg % args)

# =======================
Expand Down
14 changes: 13 additions & 1 deletion Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -2192,12 +2192,24 @@ def test_wrong_argument_subparsers_no_destination_error(self):
subparsers.add_parser('foo')
subparsers.add_parser('bar')
with self.assertRaises(ArgumentParserError) as excinfo:
parser.parse_args(('baz',))
parser.parse_args(('test',))
self.assertRegex(
excinfo.exception.stderr,
r"error: argument {foo,bar}: invalid choice: 'baz' \(choose from 'foo', 'bar'\)\n$"
)

def test_wrong_argument_subparsers_no_destination_error_with_closest_choice_input(self):
parser = ErrorRaisingArgumentParser()
subparsers = parser.add_subparsers(required=True)
subparsers.add_parser('foo')
subparsers.add_parser('bar')
with self.assertRaises(ArgumentParserError) as excinfo:
parser.parse_args(('baz',))
self.assertRegex(
excinfo.exception.stderr,
r"error: argument {foo,bar}: invalid choice: 'baz', maybe you meant bar? \(choose from 'foo', 'bar'\)\n$",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ssertionError: Regex didn't match: "error: argument {foo,bar}: invalid choice: 'baz', maybe you meant bar? \\(choose from 'foo', 'bar'\\)\\n$" not found in "usage: __main__.py [-h] {foo,bar} ...\n__main__.py: error: argument {foo,bar}: invalid choice: 'baz', maybe you meant 'bar'? (choose from 'foo', 'bar')\n"

Note: bar? vs 'bar'?

)

def test_optional_subparsers(self):
parser = ErrorRaisingArgumentParser()
subparsers = parser.add_subparsers(dest='command', required=False)
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.