Skip to content

[3.7] bpo-29553: Fix ArgumentParser.format_usage() for mutually exclusive groups (GH-14976) #15494

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 25, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.