Skip to content

gh-135227: argparse: Use help as default description in add_parser #135236

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
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
17 changes: 8 additions & 9 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -1259,17 +1259,16 @@ 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
# Handle help/description logic
help = kwargs.pop('help', None)
if 'description' not in kwargs and help is not None:
kwargs['description'] = help

# create the parser and add it to the map
# Create the parser and pseudo-action
parser = self._parser_class(**kwargs)
if choice_action is not None:
if help is not None:
choice_action = self._ChoicesPseudoAction(name, aliases, help)
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