Skip to content

Commit 6fafc25

Browse files
authored
bpo-24444: fix an error in argparse help when help for an option is blank (GH-28050)
1 parent b9e6876 commit 6fafc25

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
@@ -2164,6 +2164,42 @@ def test_help_non_breaking_spaces(self):
21642164
wrap\N{NO-BREAK SPACE}at non-breaking spaces
21652165
'''))
21662166

2167+
def test_help_blank(self):
2168+
# Issue 24444
2169+
parser = ErrorRaisingArgumentParser(
2170+
prog='PROG', description='main description')
2171+
parser.add_argument(
2172+
'foo',
2173+
help=' ')
2174+
self.assertEqual(parser.format_help(), textwrap.dedent('''\
2175+
usage: PROG [-h] foo
2176+
2177+
main description
2178+
2179+
positional arguments:
2180+
foo
2181+
2182+
options:
2183+
-h, --help show this help message and exit
2184+
'''))
2185+
2186+
parser = ErrorRaisingArgumentParser(
2187+
prog='PROG', description='main description')
2188+
parser.add_argument(
2189+
'foo', choices=[],
2190+
help='%(choices)s')
2191+
self.assertEqual(parser.format_help(), textwrap.dedent('''\
2192+
usage: PROG [-h] {}
2193+
2194+
main description
2195+
2196+
positional arguments:
2197+
{}
2198+
2199+
options:
2200+
-h, --help show this help message and exit
2201+
'''))
2202+
21672203
def test_help_alternate_prefix_chars(self):
21682204
parser = self._get_parser(prefix_chars='+:/')
21692205
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)