Skip to content

Commit 1dfe219

Browse files
[3.14] gh-142332: Fix usage formatting for positional arguments in mutually exclusive groups in argparse (GH-142333) (GH-142356)
(cherry picked from commit 70c27ce) Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
1 parent 4556b9e commit 1dfe219

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
@@ -470,16 +470,12 @@ def _get_actions_usage_parts_with_split(self, actions, groups, opt_count=None):
470470
# produce all arg strings
471471
elif not action.option_strings:
472472
default = self._get_default_metavar_for_positional(action)
473-
part = (
474-
t.summary_action
475-
+ self._format_args(action, default)
476-
+ t.reset
477-
)
478-
473+
part = self._format_args(action, default)
479474
# if it's in a group, strip the outer []
480475
if action in group_actions:
481476
if part[0] == '[' and part[-1] == ']':
482477
part = part[1:-1]
478+
part = t.summary_action + part + t.reset
483479

484480
# produce the first way to invoke the option in brackets
485481
else:

Lib/test/test_argparse.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7275,7 +7275,28 @@ def test_argparse_color(self):
72757275
),
72767276
)
72777277

7278-
def test_argparse_color_usage(self):
7278+
def test_argparse_color_mutually_exclusive_group_usage(self):
7279+
parser = argparse.ArgumentParser(color=True, prog="PROG")
7280+
group = parser.add_mutually_exclusive_group()
7281+
group.add_argument('--foo', action='store_true', help='FOO')
7282+
group.add_argument('--spam', help='SPAM')
7283+
group.add_argument('badger', nargs='*', help='BADGER')
7284+
7285+
prog = self.theme.prog
7286+
heading = self.theme.heading
7287+
long = self.theme.summary_long_option
7288+
short = self.theme.summary_short_option
7289+
label = self.theme.summary_label
7290+
pos = self.theme.summary_action
7291+
reset = self.theme.reset
7292+
7293+
self.assertEqual(parser.format_usage(),
7294+
f"{heading}usage: {reset}{prog}PROG{reset} [{short}-h{reset}] "
7295+
f"[{long}--foo{reset} | "
7296+
f"{long}--spam {label}SPAM{reset} | "
7297+
f"{pos}badger ...{reset}]\n")
7298+
7299+
def test_argparse_color_custom_usage(self):
72797300
# Arrange
72807301
parser = argparse.ArgumentParser(
72817302
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)