Skip to content

Commit fd2be6d

Browse files
bpo-24444: fix an error in argparse help when help for an option is blank (GH-28050) (GH-28931)
(cherry picked from commit 6fafc25) Co-authored-by: andrei kulakov <[email protected]>
1 parent f8473f6 commit fd2be6d

File tree

3 files changed

+44
-5
lines changed

3 files changed

+44
-5
lines changed

Lib/argparse.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -526,12 +526,13 @@ def _format_action(self, action):
526526
parts = [action_header]
527527

528528
# if there was help for the action, add lines of help text
529-
if action.help:
529+
if action.help and action.help.strip():
530530
help_text = self._expand_help(action)
531-
help_lines = self._split_lines(help_text, help_width)
532-
parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
533-
for line in help_lines[1:]:
534-
parts.append('%*s%s\n' % (help_position, '', line))
531+
if help_text:
532+
help_lines = self._split_lines(help_text, help_width)
533+
parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
534+
for line in help_lines[1:]:
535+
parts.append('%*s%s\n' % (help_position, '', line))
535536

536537
# or add a newline if the description doesn't end with one
537538
elif not action_header.endswith('\n'):

Lib/test/test_argparse.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2145,6 +2145,42 @@ def test_help_non_breaking_spaces(self):
21452145
wrap\N{NO-BREAK SPACE}at non-breaking spaces
21462146
'''))
21472147

2148+
def test_help_blank(self):
2149+
# Issue 24444
2150+
parser = ErrorRaisingArgumentParser(
2151+
prog='PROG', description='main description')
2152+
parser.add_argument(
2153+
'foo',
2154+
help=' ')
2155+
self.assertEqual(parser.format_help(), textwrap.dedent('''\
2156+
usage: PROG [-h] foo
2157+
2158+
main description
2159+
2160+
positional arguments:
2161+
foo
2162+
2163+
options:
2164+
-h, --help show this help message and exit
2165+
'''))
2166+
2167+
parser = ErrorRaisingArgumentParser(
2168+
prog='PROG', description='main description')
2169+
parser.add_argument(
2170+
'foo', choices=[],
2171+
help='%(choices)s')
2172+
self.assertEqual(parser.format_help(), textwrap.dedent('''\
2173+
usage: PROG [-h] {}
2174+
2175+
main description
2176+
2177+
positional arguments:
2178+
{}
2179+
2180+
options:
2181+
-h, --help show this help message and exit
2182+
'''))
2183+
21482184
def test_help_alternate_prefix_chars(self):
21492185
parser = self._get_parser(prefix_chars='+:/')
21502186
self.assertEqual(parser.format_usage(),
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fixed an error raised in :mod:`argparse` help display when help for an
2+
option is set to 1+ blank spaces or when *choices* arg is an empty container.

0 commit comments

Comments
 (0)