Skip to content

Commit bd8ca9a

Browse files
authored
[3.8] bpo-29553: Fix ArgumentParser.format_usage() for mutually exclusive groups (GH-14976) (GH-15494) (GH-15624)
1 parent 4bd1d05 commit bd8ca9a

File tree

2 files changed

+48
-2
lines changed

2 files changed

+48
-2
lines changed

Lib/argparse.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -405,13 +405,19 @@ def _format_actions_usage(self, actions, groups):
405405
inserts[start] += ' ['
406406
else:
407407
inserts[start] = '['
408-
inserts[end] = ']'
408+
if end in inserts:
409+
inserts[end] += ']'
410+
else:
411+
inserts[end] = ']'
409412
else:
410413
if start in inserts:
411414
inserts[start] += ' ('
412415
else:
413416
inserts[start] = '('
414-
inserts[end] = ')'
417+
if end in inserts:
418+
inserts[end] += ')'
419+
else:
420+
inserts[end] = ')'
415421
for i in range(start + 1, end):
416422
inserts[i] = '|'
417423

Lib/test/test_argparse.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2813,6 +2813,46 @@ def get_parser(self, required):
28132813
-c c help
28142814
'''
28152815

2816+
class TestMutuallyExclusiveNested(MEMixin, TestCase):
2817+
2818+
def get_parser(self, required):
2819+
parser = ErrorRaisingArgumentParser(prog='PROG')
2820+
group = parser.add_mutually_exclusive_group(required=required)
2821+
group.add_argument('-a')
2822+
group.add_argument('-b')
2823+
group2 = group.add_mutually_exclusive_group(required=required)
2824+
group2.add_argument('-c')
2825+
group2.add_argument('-d')
2826+
group3 = group2.add_mutually_exclusive_group(required=required)
2827+
group3.add_argument('-e')
2828+
group3.add_argument('-f')
2829+
return parser
2830+
2831+
usage_when_not_required = '''\
2832+
usage: PROG [-h] [-a A | -b B | [-c C | -d D | [-e E | -f F]]]
2833+
'''
2834+
usage_when_required = '''\
2835+
usage: PROG [-h] (-a A | -b B | (-c C | -d D | (-e E | -f F)))
2836+
'''
2837+
2838+
help = '''\
2839+
2840+
optional arguments:
2841+
-h, --help show this help message and exit
2842+
-a A
2843+
-b B
2844+
-c C
2845+
-d D
2846+
-e E
2847+
-f F
2848+
'''
2849+
2850+
# We are only interested in testing the behavior of format_usage().
2851+
test_failures_when_not_required = None
2852+
test_failures_when_required = None
2853+
test_successes_when_not_required = None
2854+
test_successes_when_required = None
2855+
28162856
# =================================================
28172857
# Mutually exclusive group in parent parser tests
28182858
# =================================================

0 commit comments

Comments
 (0)