diff --git a/Lib/argparse.py b/Lib/argparse.py index 83258cf3e0f37d..a65a84a9a7dac7 100644 --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -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 diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py index 08ff41368d9bb0..12cbb78590a63b 100644 --- a/Lib/test/test_argparse.py +++ b/Lib/test/test_argparse.py @@ -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 # ============ diff --git a/Misc/NEWS.d/next/Library/2025-06-07-15-10-22.gh-issue-135227.LPeDGt.rst b/Misc/NEWS.d/next/Library/2025-06-07-15-10-22.gh-issue-135227.LPeDGt.rst new file mode 100644 index 00000000000000..2a936933c826ba --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-06-07-15-10-22.gh-issue-135227.LPeDGt.rst @@ -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.