Skip to content

Commit 0ed56ed

Browse files
GH-64532: Include parent's required optional arguments in subparser usage (#142355)
1 parent 70c27ce commit 0ed56ed

File tree

3 files changed

+15
-2
lines changed

3 files changed

+15
-2
lines changed

Lib/argparse.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2004,14 +2004,16 @@ def add_subparsers(self, **kwargs):
20042004
self._subparsers = self._positionals
20052005

20062006
# prog defaults to the usage message of this parser, skipping
2007-
# optional arguments and with no "usage:" prefix
2007+
# non-required optional arguments and with no "usage:" prefix
20082008
if kwargs.get('prog') is None:
20092009
# Create formatter without color to avoid storing ANSI codes in prog
20102010
formatter = self.formatter_class(prog=self.prog)
20112011
formatter._set_color(False)
20122012
positionals = self._get_positional_actions()
2013+
required_optionals = [action for action in self._get_optional_actions()
2014+
if action.required]
20132015
groups = self._mutually_exclusive_groups
2014-
formatter.add_usage(None, positionals, groups, '')
2016+
formatter.add_usage(None, required_optionals + positionals, groups, '')
20152017
kwargs['prog'] = formatter.format_help().strip()
20162018

20172019
# create the parsers action and add it to the positionals list

Lib/test/test_argparse.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2770,6 +2770,16 @@ def test_optional_subparsers(self):
27702770
ret = parser.parse_args(())
27712771
self.assertIsNone(ret.command)
27722772

2773+
def test_subparser_help_with_parent_required_optional(self):
2774+
parser = ErrorRaisingArgumentParser(prog='PROG')
2775+
parser.add_argument('--foo', required=True)
2776+
parser.add_argument('--bar')
2777+
subparsers = parser.add_subparsers()
2778+
parser_sub = subparsers.add_parser('sub')
2779+
parser_sub.add_argument('arg')
2780+
self.assertEqual(parser_sub.format_usage(),
2781+
'usage: PROG --foo FOO sub [-h] arg\n')
2782+
27732783
def test_help(self):
27742784
self.assertEqual(self.parser.format_usage(),
27752785
'usage: PROG [-h] [--foo] bar {1,2,3} ...\n')
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Subparser help now includes required optional arguments from the parent parser in the usage, making it clearer what arguments are needed to run a subcommand. Patch by Savannah Ostrowski.

0 commit comments

Comments
 (0)