From 617616e1c5254635eafefba3316437f84df5cbef Mon Sep 17 00:00:00 2001 From: Lucas Cimon <925560+Lucas-C@users.noreply.github.com> Date: Sun, 1 Nov 2020 12:27:29 +0100 Subject: [PATCH] bpo-38584: fix a bug in argparse with whitespace-only help messages --- Lib/argparse.py | 3 ++- Lib/test/test_argparse.py | 9 +++++++++ .../Library/2020-11-01-12-27-34.bpo-38584.S6K8sF.rst | 1 + 3 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2020-11-01-12-27-34.bpo-38584.S6K8sF.rst diff --git a/Lib/argparse.py b/Lib/argparse.py index 2fb1da59f94..f6cb7129e14 100644 --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -529,7 +529,8 @@ class HelpFormatter(object): if action.help: help_text = self._expand_help(action) help_lines = self._split_lines(help_text, help_width) - parts.append('%*s%s\n' % (indent_first, '', help_lines[0])) + if help_lines: + parts.append('%*s%s\n' % (indent_first, '', help_lines[0])) for line in help_lines[1:]: parts.append('%*s%s\n' % (help_position, '', line)) diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py index e98c15b11af..1ea02998eec 100644 --- a/Lib/test/test_argparse.py +++ b/Lib/test/test_argparse.py @@ -4688,6 +4688,15 @@ class TestOptionalsHelpVersionActions(TestCase): self.assertPrintHelpExit(parser, format % '--help') self.assertRaises(AttributeError, getattr, parser, 'format_version') + def test_whitespace_help(self): + for formatter_class in (argparse.ArgumentDefaultsHelpFormatter, argparse.HelpFormatter, + argparse.MetavarTypeHelpFormatter, + argparse.RawDescriptionHelpFormatter, argparse.RawTextHelpFormatter): + parser = argparse.ArgumentParser(formatter_class=formatter_class) + parser.add_argument('--foo', action='store_true', help=' ') + parser.add_argument('bar', type=float, help=' ') + parser.format_help() # does not raise any error + # ====================== # str() and repr() tests diff --git a/Misc/NEWS.d/next/Library/2020-11-01-12-27-34.bpo-38584.S6K8sF.rst b/Misc/NEWS.d/next/Library/2020-11-01-12-27-34.bpo-38584.S6K8sF.rst new file mode 100644 index 00000000000..6b1206fd790 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2020-11-01-12-27-34.bpo-38584.S6K8sF.rst @@ -0,0 +1 @@ +Fix a minor bug in argparse with whitespace-only argument help messages