Skip to content

Commit

Permalink
bpo-29553: Fix ArgumentParser.format_usage() for mutually exclusive g…
Browse files Browse the repository at this point in the history
…roups (GH-14976)

Co-authored-by: Andrew Nester <andrew.nester.dev@gmail.com>
Co-authored-by: Flavian Hautbois <flavianh@sicara.com>

(cherry picked from commit da27d9b)
  • Loading branch information
miss-islington authored and berkerpeksag committed Aug 25, 2019
1 parent f2b468d commit 31ea447
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 2 deletions.
10 changes: 8 additions & 2 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -407,13 +407,19 @@ def _format_actions_usage(self, actions, groups):
inserts[start] += ' ['
else:
inserts[start] = '['
inserts[end] = ']'
if end in inserts:
inserts[end] += ']'
else:
inserts[end] = ']'
else:
if start in inserts:
inserts[start] += ' ('
else:
inserts[start] = '('
inserts[end] = ')'
if end in inserts:
inserts[end] += ')'
else:
inserts[end] = ')'
for i in range(start + 1, end):
inserts[i] = '|'

Expand Down
40 changes: 40 additions & 0 deletions Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -2772,6 +2772,46 @@ def get_parser(self, required):
-c c help
'''

class TestMutuallyExclusiveNested(MEMixin, TestCase):

def get_parser(self, required):
parser = ErrorRaisingArgumentParser(prog='PROG')
group = parser.add_mutually_exclusive_group(required=required)
group.add_argument('-a')
group.add_argument('-b')
group2 = group.add_mutually_exclusive_group(required=required)
group2.add_argument('-c')
group2.add_argument('-d')
group3 = group2.add_mutually_exclusive_group(required=required)
group3.add_argument('-e')
group3.add_argument('-f')
return parser

usage_when_not_required = '''\
usage: PROG [-h] [-a A | -b B | [-c C | -d D | [-e E | -f F]]]
'''
usage_when_required = '''\
usage: PROG [-h] (-a A | -b B | (-c C | -d D | (-e E | -f F)))
'''

help = '''\
optional arguments:
-h, --help show this help message and exit
-a A
-b B
-c C
-d D
-e E
-f F
'''

# We are only interested in testing the behavior of format_usage().
test_failures_when_not_required = None
test_failures_when_required = None
test_successes_when_not_required = None
test_successes_when_required = None

# =================================================
# Mutually exclusive group in parent parser tests
# =================================================
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fixed :meth:`argparse.ArgumentParser.format_usage` for mutually exclusive groups.
Patch by Andrew Nester.

0 comments on commit 31ea447

Please sign in to comment.