Skip to content

Commit 70c27ce

Browse files
gh-142332: Fix usage formatting for positional arguments in mutually exclusive groups in argparse (GH-142333)
1 parent 5be3405 commit 70c27ce

File tree

3 files changed

+26
-7
lines changed

3 files changed

+26
-7
lines changed

Lib/argparse.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -467,16 +467,12 @@ def _get_actions_usage_parts_with_split(self, actions, groups, opt_count=None):
467467
# produce all arg strings
468468
elif not action.option_strings:
469469
default = self._get_default_metavar_for_positional(action)
470-
part = (
471-
t.summary_action
472-
+ self._format_args(action, default)
473-
+ t.reset
474-
)
475-
470+
part = self._format_args(action, default)
476471
# if it's in a group, strip the outer []
477472
if action in group_actions:
478473
if part[0] == '[' and part[-1] == ']':
479474
part = part[1:-1]
475+
part = t.summary_action + part + t.reset
480476

481477
# produce the first way to invoke the option in brackets
482478
else:

Lib/test/test_argparse.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7361,7 +7361,28 @@ def test_argparse_color(self):
73617361
),
73627362
)
73637363

7364-
def test_argparse_color_usage(self):
7364+
def test_argparse_color_mutually_exclusive_group_usage(self):
7365+
parser = argparse.ArgumentParser(color=True, prog="PROG")
7366+
group = parser.add_mutually_exclusive_group()
7367+
group.add_argument('--foo', action='store_true', help='FOO')
7368+
group.add_argument('--spam', help='SPAM')
7369+
group.add_argument('badger', nargs='*', help='BADGER')
7370+
7371+
prog = self.theme.prog
7372+
heading = self.theme.heading
7373+
long = self.theme.summary_long_option
7374+
short = self.theme.summary_short_option
7375+
label = self.theme.summary_label
7376+
pos = self.theme.summary_action
7377+
reset = self.theme.reset
7378+
7379+
self.assertEqual(parser.format_usage(),
7380+
f"{heading}usage: {reset}{prog}PROG{reset} [{short}-h{reset}] "
7381+
f"[{long}--foo{reset} | "
7382+
f"{long}--spam {label}SPAM{reset} | "
7383+
f"{pos}badger ...{reset}]\n")
7384+
7385+
def test_argparse_color_custom_usage(self):
73657386
# Arrange
73667387
parser = argparse.ArgumentParser(
73677388
add_help=False,
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix usage formatting for positional arguments in mutually exclusive groups in :mod:`argparse`.
2+
in :mod:`argparse`.

0 commit comments

Comments
 (0)