Skip to content

Commit f1a2417

Browse files
pythongh-61181: Fix support of choices with string value in argparse (pythonGH-124578)
Substrings of the specified string no longer considered valid values.
1 parent dac4ec5 commit f1a2417

File tree

4 files changed

+17
-11
lines changed

4 files changed

+17
-11
lines changed

Doc/library/argparse.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1823,7 +1823,7 @@ Sub-commands
18231823
>>>
18241824
>>> # create the parser for the "b" command
18251825
>>> parser_b = subparsers.add_parser('b', help='b help')
1826-
>>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1826+
>>> parser_b.add_argument('--baz', choices=('X', 'Y', 'Z'), help='baz help')
18271827
>>>
18281828
>>> # parse some argument lists
18291829
>>> parser.parse_args(['a', '12'])

Lib/argparse.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2552,11 +2552,15 @@ def _get_value(self, action, arg_string):
25522552

25532553
def _check_value(self, action, value):
25542554
# converted value must be one of the choices (if specified)
2555-
if action.choices is not None and value not in action.choices:
2556-
args = {'value': value,
2557-
'choices': ', '.join(map(repr, action.choices))}
2558-
msg = _('invalid choice: %(value)r (choose from %(choices)s)')
2559-
raise ArgumentError(action, msg % args)
2555+
choices = action.choices
2556+
if choices is not None:
2557+
if isinstance(choices, str):
2558+
choices = iter(choices)
2559+
if value not in choices:
2560+
args = {'value': value,
2561+
'choices': ', '.join(map(repr, action.choices))}
2562+
msg = _('invalid choice: %(value)r (choose from %(choices)s)')
2563+
raise ArgumentError(action, msg % args)
25602564

25612565
# =======================
25622566
# Help-formatting methods

Lib/test/test_argparse.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -686,7 +686,7 @@ class TestOptionalsChoices(ParserTestCase):
686686
argument_signatures = [
687687
Sig('-f', choices='abc'),
688688
Sig('-g', type=int, choices=range(5))]
689-
failures = ['a', '-f d', '-fad', '-ga', '-g 6']
689+
failures = ['a', '-f d', '-f ab', '-fad', '-ga', '-g 6']
690690
successes = [
691691
('', NS(f=None, g=None)),
692692
('-f a', NS(f='a', g=None)),
@@ -2270,14 +2270,14 @@ def _get_parser(self, subparser_help=False, prefix_chars=None,
22702270
parser1_kwargs['aliases'] = ['1alias1', '1alias2']
22712271
parser1 = subparsers.add_parser('1', **parser1_kwargs)
22722272
parser1.add_argument('-w', type=int, help='w help')
2273-
parser1.add_argument('x', choices='abc', help='x help')
2273+
parser1.add_argument('x', choices=['a', 'b', 'c'], help='x help')
22742274

22752275
# add second sub-parser
22762276
parser2_kwargs = dict(description='2 description')
22772277
if subparser_help:
22782278
parser2_kwargs['help'] = '2 help'
22792279
parser2 = subparsers.add_parser('2', **parser2_kwargs)
2280-
parser2.add_argument('-y', choices='123', help='y help')
2280+
parser2.add_argument('-y', choices=['1', '2', '3'], help='y help')
22812281
parser2.add_argument('z', type=complex, nargs='*', help='z help')
22822282

22832283
# add third sub-parser
@@ -4618,7 +4618,7 @@ class TestHelpVariableExpansion(HelpTestCase):
46184618
help='x %(prog)s %(default)s %(type)s %%'),
46194619
Sig('-y', action='store_const', default=42, const='XXX',
46204620
help='y %(prog)s %(default)s %(const)s'),
4621-
Sig('--foo', choices='abc',
4621+
Sig('--foo', choices=['a', 'b', 'c'],
46224622
help='foo %(prog)s %(default)s %(choices)s'),
46234623
Sig('--bar', default='baz', choices=[1, 2], metavar='BBB',
46244624
help='bar %(prog)s %(default)s %(dest)s'),
@@ -5281,7 +5281,7 @@ def test_no_argument_actions(self):
52815281
for action in ['store_const', 'store_true', 'store_false',
52825282
'append_const', 'count']:
52835283
for attrs in [dict(type=int), dict(nargs='+'),
5284-
dict(choices='ab')]:
5284+
dict(choices=['a', 'b'])]:
52855285
self.assertTypeError('-x', action=action, **attrs)
52865286

52875287
def test_no_argument_no_const_actions(self):
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix support of :ref:`choices` with string value in :mod:`argparse`. Substrings
2+
of the specified string no longer considered valid values.

0 commit comments

Comments
 (0)