Skip to content

Commit f54bc0e

Browse files
committed
Pass choices through type before _check_value
1 parent a16586c commit f54bc0e

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

Lib/argparse.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1777,6 +1777,8 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
17771777
error info when an error occurs
17781778
- suggest_on_error - Enables suggestions for mistyped argument choices
17791779
and subparser names. (default: ``False``)
1780+
- convert_choices - Runs the ``choices`` through the ``type`` function
1781+
during checking. (default: ``False``)
17801782
"""
17811783

17821784
def __init__(self,
@@ -1793,7 +1795,8 @@ def __init__(self,
17931795
add_help=True,
17941796
allow_abbrev=True,
17951797
exit_on_error=True,
1796-
suggest_on_error=False):
1798+
suggest_on_error=False,
1799+
convert_choices=False):
17971800

17981801
superinit = super(ArgumentParser, self).__init__
17991802
superinit(description=description,
@@ -1810,6 +1813,7 @@ def __init__(self,
18101813
self.allow_abbrev = allow_abbrev
18111814
self.exit_on_error = exit_on_error
18121815
self.suggest_on_error = suggest_on_error
1816+
self.convert_choices = convert_choices
18131817

18141818
add_group = self.add_argument_group
18151819
self._positionals = add_group(_('positional arguments'))
@@ -2581,7 +2585,17 @@ def _check_value(self, action, value):
25812585
if isinstance(choices, str):
25822586
choices = iter(choices)
25832587

2584-
if value not in choices:
2588+
typed_choices = []
2589+
if (self.convert_choices and
2590+
self.type and
2591+
isinstance(self.choices[0], str)):
2592+
try:
2593+
typed_choices = [acton.type[v] for v in choices]
2594+
except Exception:
2595+
# We use a blanket catch here, because type is user provided.
2596+
pass
2597+
2598+
if value not in choices and value not in typed_choices:
25852599
args = {'value': str(value),
25862600
'choices': ', '.join(map(str, action.choices))}
25872601
msg = _('invalid choice: %(value)r (choose from %(choices)s)')

0 commit comments

Comments
 (0)