Skip to content

Commit 7677be5

Browse files
[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 f1a2417) Co-authored-by: Serhiy Storchaka <[email protected]>
1 parent 71a2b8d commit 7677be5

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
@@ -1774,7 +1774,7 @@ Sub-commands
17741774
>>>
17751775
>>> # create the parser for the "b" command
17761776
>>> parser_b = subparsers.add_parser('b', help='b help')
1777-
>>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1777+
>>> parser_b.add_argument('--baz', choices=('X', 'Y', 'Z'), help='baz help')
17781778
>>>
17791779
>>> # parse some argument lists
17801780
>>> parser.parse_args(['a', '12'])

Lib/argparse.py

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

25902590
def _check_value(self, action, value):
25912591
# converted value must be one of the choices (if specified)
2592-
if action.choices is not None and value not in action.choices:
2593-
args = {'value': value,
2594-
'choices': ', '.join(map(repr, action.choices))}
2595-
msg = _('invalid choice: %(value)r (choose from %(choices)s)')
2596-
raise ArgumentError(action, msg % args)
2592+
choices = action.choices
2593+
if choices is not None:
2594+
if isinstance(choices, str):
2595+
choices = iter(choices)
2596+
if value not in choices:
2597+
args = {'value': value,
2598+
'choices': ', '.join(map(repr, action.choices))}
2599+
msg = _('invalid choice: %(value)r (choose from %(choices)s)')
2600+
raise ArgumentError(action, msg % args)
25972601

25982602
# =======================
25992603
# 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)),
@@ -2227,14 +2227,14 @@ def _get_parser(self, subparser_help=False, prefix_chars=None,
22272227
parser1_kwargs['aliases'] = ['1alias1', '1alias2']
22282228
parser1 = subparsers.add_parser('1', **parser1_kwargs)
22292229
parser1.add_argument('-w', type=int, help='w help')
2230-
parser1.add_argument('x', choices='abc', help='x help')
2230+
parser1.add_argument('x', choices=['a', 'b', 'c'], help='x help')
22312231

22322232
# add second sub-parser
22332233
parser2_kwargs = dict(description='2 description')
22342234
if subparser_help:
22352235
parser2_kwargs['help'] = '2 help'
22362236
parser2 = subparsers.add_parser('2', **parser2_kwargs)
2237-
parser2.add_argument('-y', choices='123', help='y help')
2237+
parser2.add_argument('-y', choices=['1', '2', '3'], help='y help')
22382238
parser2.add_argument('z', type=complex, nargs='*', help='z help')
22392239

22402240
# add third sub-parser
@@ -4397,7 +4397,7 @@ class TestHelpVariableExpansion(HelpTestCase):
43974397
help='x %(prog)s %(default)s %(type)s %%'),
43984398
Sig('-y', action='store_const', default=42, const='XXX',
43994399
help='y %(prog)s %(default)s %(const)s'),
4400-
Sig('--foo', choices='abc',
4400+
Sig('--foo', choices=['a', 'b', 'c'],
44014401
help='foo %(prog)s %(default)s %(choices)s'),
44024402
Sig('--bar', default='baz', choices=[1, 2], metavar='BBB',
44034403
help='bar %(prog)s %(default)s %(dest)s'),
@@ -5057,7 +5057,7 @@ def test_no_argument_actions(self):
50575057
for action in ['store_const', 'store_true', 'store_false',
50585058
'append_const', 'count']:
50595059
for attrs in [dict(type=int), dict(nargs='+'),
5060-
dict(choices='ab')]:
5060+
dict(choices=['a', 'b'])]:
50615061
self.assertTypeError('-x', action=action, **attrs)
50625062

50635063
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)