Skip to content
Open
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
19 changes: 10 additions & 9 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -1259,17 +1259,18 @@ def add_parser(self, name, *, deprecated=False, **kwargs):
if alias in self._name_parser_map:
raise ValueError(f'conflicting subparser alias: {alias}')

# create a pseudo-action to hold the choice help
if 'help' in kwargs:
help = kwargs.pop('help')
choice_action = self._ChoicesPseudoAction(name, aliases, help)
self._choices_actions.append(choice_action)
else:
choice_action = None
help_provided = 'help' in kwargs
help_text = kwargs.pop('help', None) if help_provided else None

# create the parser and add it to the map
# Set description default ONLY if:
if 'description' not in kwargs and help_text is not None:
kwargs['description'] = help_text

# Create the parser and pseudo-action
parser = self._parser_class(**kwargs)
if choice_action is not None:
if help_provided:
choice_action = self._ChoicesPseudoAction(name, aliases, help_text)
self._choices_actions.append(choice_action)
parser._check_help(choice_action)
self._name_parser_map[name] = parser

Expand Down
13 changes: 13 additions & 0 deletions Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -2934,6 +2934,19 @@ def test_alias_help(self):
3 3 help
"""))

def test_help_sets_default_description(self):
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest="command")

sp1 = subparsers.add_parser("a", help="help a")
self.assertEqual(sp1.description, "help a")

sp2 = subparsers.add_parser("b", help="help b", description="explicit desc")
self.assertEqual(sp2.description, "explicit desc")

sp3 = subparsers.add_parser("c")
self.assertIsNone(sp3.description)

# ============
# Groups tests
# ============
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
The :meth:`!add_parser` method of the special action object returned by
:meth:`argparse.ArgumentParser.add_subparsers` now uses the *help* value as
the default *description* if none is provided. Patch by Swayam.
Loading