[3.14] gh-112527: Fix help text for required options in argparse (GH-112528) (GH-142475)

For optional arguments with required=True, the ArgumentDefaultsHelpFormatter
would always add a " (default: None)" to the end of the help text.
Since that's a bit misleading, it is removed with this commit.
(cherry picked from commit 1adb17b1a2)

Co-authored-by: Fabian Henze <32638720+henzef@users.noreply.github.com>
This commit is contained in:
Serhiy Storchaka 2025-12-09 19:35:49 +02:00 committed by GitHub
parent 69ecb4c234
commit dafac8a47a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 14 additions and 7 deletions

View file

@ -739,11 +739,14 @@ def _get_help_string(self, action):
if help is None:
help = ''
if '%(default)' not in help:
if action.default is not SUPPRESS:
defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
if action.option_strings or action.nargs in defaulting_nargs:
help += _(' (default: %(default)s)')
if (
'%(default)' not in help
and action.default is not SUPPRESS
and not action.required
):
defaulting_nargs = (OPTIONAL, ZERO_OR_MORE)
if action.option_strings or action.nargs in defaulting_nargs:
help += _(' (default: %(default)s)')
return help

View file

@ -5328,6 +5328,7 @@ class TestHelpArgumentDefaults(HelpTestCase):
argument_signatures = [
Sig('--foo', help='foo help - oh and by the way, %(default)s'),
Sig('--bar', action='store_true', help='bar help'),
Sig('--required', required=True, help='some help'),
Sig('--taz', action=argparse.BooleanOptionalAction,
help='Whether to taz it', default=True),
Sig('--corge', action=argparse.BooleanOptionalAction,
@ -5341,8 +5342,8 @@ class TestHelpArgumentDefaults(HelpTestCase):
[Sig('--baz', type=int, default=42, help='baz help')]),
]
usage = '''\
usage: PROG [-h] [--foo FOO] [--bar] [--taz | --no-taz] [--corge | --no-corge]
[--quux QUUX] [--baz BAZ]
usage: PROG [-h] [--foo FOO] [--bar] --required REQUIRED [--taz | --no-taz]
[--corge | --no-corge] [--quux QUUX] [--baz BAZ]
spam [badger]
'''
help = usage + '''\
@ -5357,6 +5358,7 @@ class TestHelpArgumentDefaults(HelpTestCase):
-h, --help show this help message and exit
--foo FOO foo help - oh and by the way, None
--bar bar help (default: False)
--required REQUIRED some help
--taz, --no-taz Whether to taz it (default: True)
--corge, --no-corge Whether to corge it
--quux QUUX Set the quux (default: 42)

View file

@ -0,0 +1,2 @@
The help text for required options in :mod:`argparse` no
longer extended with " (default: None)".