Skip to content

Commit 6925e5b

Browse files
[3.13] gh-58573: Fix conflicts between abbreviated long options in the parent parser and subparsers in argparse (GH-124631) (GH-124760)
Check for ambiguous options if the option is consumed, not when it is parsed. (cherry picked from commit 3f27153)
1 parent 0a04677 commit 6925e5b

File tree

3 files changed

+52
-34
lines changed

3 files changed

+52
-34
lines changed

Lib/argparse.py

+28-34
Original file line numberDiff line numberDiff line change
@@ -1956,11 +1956,11 @@ def _parse_known_args(self, arg_strings, namespace):
19561956
# otherwise, add the arg to the arg strings
19571957
# and note the index if it was an option
19581958
else:
1959-
option_tuple = self._parse_optional(arg_string)
1960-
if option_tuple is None:
1959+
option_tuples = self._parse_optional(arg_string)
1960+
if option_tuples is None:
19611961
pattern = 'A'
19621962
else:
1963-
option_string_indices[i] = option_tuple
1963+
option_string_indices[i] = option_tuples
19641964
pattern = 'O'
19651965
arg_string_pattern_parts.append(pattern)
19661966

@@ -1995,8 +1995,16 @@ def take_action(action, argument_strings, option_string=None):
19951995
def consume_optional(start_index):
19961996

19971997
# get the optional identified at this index
1998-
option_tuple = option_string_indices[start_index]
1999-
action, option_string, sep, explicit_arg = option_tuple
1998+
option_tuples = option_string_indices[start_index]
1999+
# if multiple actions match, the option string was ambiguous
2000+
if len(option_tuples) > 1:
2001+
options = ', '.join([option_string
2002+
for action, option_string, sep, explicit_arg in option_tuples])
2003+
args = {'option': arg_string, 'matches': options}
2004+
msg = _('ambiguous option: %(option)s could match %(matches)s')
2005+
raise ArgumentError(None, msg % args)
2006+
2007+
action, option_string, sep, explicit_arg = option_tuples[0]
20002008

20012009
# identify additional optionals in the same arg string
20022010
# (e.g. -xyz is the same as -x -y -z if no args are required)
@@ -2282,7 +2290,7 @@ def _parse_optional(self, arg_string):
22822290
# if the option string is present in the parser, return the action
22832291
if arg_string in self._option_string_actions:
22842292
action = self._option_string_actions[arg_string]
2285-
return action, arg_string, None, None
2293+
return [(action, arg_string, None, None)]
22862294

22872295
# if it's just a single character, it was meant to be positional
22882296
if len(arg_string) == 1:
@@ -2292,25 +2300,14 @@ def _parse_optional(self, arg_string):
22922300
option_string, sep, explicit_arg = arg_string.partition('=')
22932301
if sep and option_string in self._option_string_actions:
22942302
action = self._option_string_actions[option_string]
2295-
return action, option_string, sep, explicit_arg
2303+
return [(action, option_string, sep, explicit_arg)]
22962304

22972305
# search through all possible prefixes of the option string
22982306
# and all actions in the parser for possible interpretations
22992307
option_tuples = self._get_option_tuples(arg_string)
23002308

2301-
# if multiple actions match, the option string was ambiguous
2302-
if len(option_tuples) > 1:
2303-
options = ', '.join([option_string
2304-
for action, option_string, sep, explicit_arg in option_tuples])
2305-
args = {'option': arg_string, 'matches': options}
2306-
msg = _('ambiguous option: %(option)s could match %(matches)s')
2307-
raise ArgumentError(None, msg % args)
2308-
2309-
# if exactly one action matched, this segmentation is good,
2310-
# so return the parsed action
2311-
elif len(option_tuples) == 1:
2312-
option_tuple, = option_tuples
2313-
return option_tuple
2309+
if option_tuples:
2310+
return option_tuples
23142311

23152312
# if it was not found as an option, but it looks like a negative
23162313
# number, it was meant to be positional
@@ -2325,7 +2322,7 @@ def _parse_optional(self, arg_string):
23252322

23262323
# it was meant to be an optional but there is no such option
23272324
# in this parser (though it might be a valid option in a subparser)
2328-
return None, arg_string, None, None
2325+
return [(None, arg_string, None, None)]
23292326

23302327
def _get_option_tuples(self, option_string):
23312328
result = []
@@ -2375,43 +2372,40 @@ def _get_nargs_pattern(self, action):
23752372
# in all examples below, we have to allow for '--' args
23762373
# which are represented as '-' in the pattern
23772374
nargs = action.nargs
2375+
# if this is an optional action, -- is not allowed
2376+
option = action.option_strings
23782377

23792378
# the default (None) is assumed to be a single argument
23802379
if nargs is None:
2381-
nargs_pattern = '(-*A-*)'
2380+
nargs_pattern = '([A])' if option else '(-*A-*)'
23822381

23832382
# allow zero or one arguments
23842383
elif nargs == OPTIONAL:
2385-
nargs_pattern = '(-*A?-*)'
2384+
nargs_pattern = '(A?)' if option else '(-*A?-*)'
23862385

23872386
# allow zero or more arguments
23882387
elif nargs == ZERO_OR_MORE:
2389-
nargs_pattern = '(-*[A-]*)'
2388+
nargs_pattern = '(A*)' if option else '(-*[A-]*)'
23902389

23912390
# allow one or more arguments
23922391
elif nargs == ONE_OR_MORE:
2393-
nargs_pattern = '(-*A[A-]*)'
2392+
nargs_pattern = '(A+)' if option else '(-*A[A-]*)'
23942393

23952394
# allow any number of options or arguments
23962395
elif nargs == REMAINDER:
2397-
nargs_pattern = '([-AO]*)'
2396+
nargs_pattern = '([AO]*)' if option else '(.*)'
23982397

23992398
# allow one argument followed by any number of options or arguments
24002399
elif nargs == PARSER:
2401-
nargs_pattern = '(-*A[-AO]*)'
2400+
nargs_pattern = '(A[AO]*)' if option else '(-*A[-AO]*)'
24022401

24032402
# suppress action, like nargs=0
24042403
elif nargs == SUPPRESS:
2405-
nargs_pattern = '(-*-*)'
2404+
nargs_pattern = '()' if option else '(-*)'
24062405

24072406
# all others should be integers
24082407
else:
2409-
nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
2410-
2411-
# if this is an optional action, -- is not allowed
2412-
if action.option_strings:
2413-
nargs_pattern = nargs_pattern.replace('-*', '')
2414-
nargs_pattern = nargs_pattern.replace('-', '')
2408+
nargs_pattern = '([AO]{%d})' % nargs if option else '((?:-*A){%d}-*)' % nargs
24152409

24162410
# return the pattern
24172411
return nargs_pattern

Lib/test/test_argparse.py

+22
Original file line numberDiff line numberDiff line change
@@ -2377,6 +2377,28 @@ class C:
23772377
self.assertEqual(C.w, 7)
23782378
self.assertEqual(C.x, 'b')
23792379

2380+
def test_abbreviation(self):
2381+
parser = ErrorRaisingArgumentParser()
2382+
parser.add_argument('--foodle')
2383+
parser.add_argument('--foonly')
2384+
subparsers = parser.add_subparsers()
2385+
parser1 = subparsers.add_parser('bar')
2386+
parser1.add_argument('--fo')
2387+
parser1.add_argument('--foonew')
2388+
2389+
self.assertEqual(parser.parse_args(['--food', 'baz', 'bar']),
2390+
NS(foodle='baz', foonly=None, fo=None, foonew=None))
2391+
self.assertEqual(parser.parse_args(['--foon', 'baz', 'bar']),
2392+
NS(foodle=None, foonly='baz', fo=None, foonew=None))
2393+
self.assertArgumentParserError(parser.parse_args, ['--fo', 'baz', 'bar'])
2394+
self.assertEqual(parser.parse_args(['bar', '--fo', 'baz']),
2395+
NS(foodle=None, foonly=None, fo='baz', foonew=None))
2396+
self.assertEqual(parser.parse_args(['bar', '--foo', 'baz']),
2397+
NS(foodle=None, foonly=None, fo=None, foonew='baz'))
2398+
self.assertEqual(parser.parse_args(['bar', '--foon', 'baz']),
2399+
NS(foodle=None, foonly=None, fo=None, foonew='baz'))
2400+
self.assertArgumentParserError(parser.parse_args, ['bar', '--food', 'baz'])
2401+
23802402
def test_parse_known_args_with_single_dash_option(self):
23812403
parser = ErrorRaisingArgumentParser()
23822404
parser.add_argument('-k', '--known', action='count', default=0)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix conflicts between abbreviated long options in the parent parser and
2+
subparsers in :mod:`argparse`.

0 commit comments

Comments
 (0)