Skip to content

Commit ca9d0b0

Browse files
gh-142332: Fix formatting the usage for positional argument in mutually exclusive group in argparse
1 parent eba449a commit ca9d0b0

3 files changed

Lines changed: 26 additions & 7 deletions

File tree

Lib/argparse.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -450,16 +450,12 @@ def _get_actions_usage_parts(self, actions, groups):
450450
# produce all arg strings
451451
elif not action.option_strings:
452452
default = self._get_default_metavar_for_positional(action)
453-
part = (
454-
t.summary_action
455-
+ self._format_args(action, default)
456-
+ t.reset
457-
)
458-
453+
part = self._format_args(action, default)
459454
# if it's in a group, strip the outer []
460455
if action in group_actions:
461456
if part[0] == '[' and part[-1] == ']':
462457
part = part[1:-1]
458+
part = t.summary_action + part + t.reset
463459

464460
# produce the first way to invoke the option in brackets
465461
else:

Lib/test/test_argparse.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7342,7 +7342,28 @@ def test_argparse_color(self):
73427342
),
73437343
)
73447344

7345-
def test_argparse_color_usage(self):
7345+
def test_argparse_color_mutually_exclusive_group_usage(self):
7346+
parser = argparse.ArgumentParser(color=True, prog="PROG")
7347+
group = parser.add_mutually_exclusive_group()
7348+
group.add_argument('--foo', action='store_true', help='FOO')
7349+
group.add_argument('--spam', help='SPAM')
7350+
group.add_argument('badger', nargs='*', help='BADGER')
7351+
7352+
prog = self.theme.prog
7353+
heading = self.theme.heading
7354+
long = self.theme.summary_long_option
7355+
short = self.theme.summary_short_option
7356+
label = self.theme.summary_label
7357+
pos = self.theme.summary_action
7358+
reset = self.theme.reset
7359+
7360+
self.assertEqual(parser.format_usage(),
7361+
f"{heading}usage: {reset}{prog}PROG{reset} [{short}-h{reset}] "
7362+
f"[{long}--foo{reset} | "
7363+
f"{long}--spam {label}SPAM{reset} | "
7364+
f"{pos}badger ...{reset}]\n")
7365+
7366+
def test_argparse_color_custom_usage(self):
73467367
# Arrange
73477368
parser = argparse.ArgumentParser(
73487369
add_help=False,
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix formatting the usage for positional argument in mutually exclusive group
2+
in :mod:`argparse`.

0 commit comments

Comments
 (0)