[3.12] gh-61181: Fix support of choices with string value in argparse (GH-124578) (GH-124756)

Substrings of the specified string no longer considered valid values.
(cherry picked from commit f1a2417b9e)

Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
This commit is contained in:
Miss Islington (bot) 2024-09-29 10:32:51 +02:00 committed by GitHub
parent 71a2b8d185
commit 7677be5ee6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 17 additions and 11 deletions

View file

@ -2589,11 +2589,15 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
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)')
raise ArgumentError(action, msg % args)
choices = action.choices
if choices is not None:
if isinstance(choices, str):
choices = iter(choices)
if value not in choices:
args = {'value': value,
'choices': ', '.join(map(repr, action.choices))}
msg = _('invalid choice: %(value)r (choose from %(choices)s)')
raise ArgumentError(action, msg % args)
# =======================
# Help-formatting methods