[issue38584] argparse: Specifying a whitespace-only help message to a positional arg triggers an IndexError when displaying --help

paul j3 report at bugs.python.org
Thu Oct 24 13:15:15 EDT 2019


paul j3 <ajipanca at gmail.com> added the comment:

So the error occurs in HelpFormatter._format_action when 'help_lines' is an empty list:

        ....
        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]))
            for line in help_lines[1:]:
                parts.append('%*s%s\n' % (help_position, '', line))

It occurs with both optionals and positionals.  It does not occur with argparse.RawTextHelpFormatter.

The default _split_lines:

    def _split_lines(self, text, width):
        text = self._whitespace_matcher.sub(' ', text).strip()
        return _textwrap.wrap(text, width)

Because of the 'strip' it treats a help with space as empty

In [27]: f._split_lines('',40)                                                  
Out[27]: []
In [28]: f._split_lines('test',40)                                              
Out[28]: ['test']
In [29]: f._split_lines(' ',40)                                                 
Out[29]: []

None or '' don't trigger this because they are weeded out by the 'if action.help:' line.

Maybe the change proposed here, to skip the problem line if 'help_lines' is empty is the right one.  Assuming a list is non-empty can be dangerous.  But it would be wise to test the patch with the alternative formatters like the RawText.  

It may also be worth thinking about correcting the issue in _split_lines(), which is shorter.  The only difference in  RawTextHelpFormatter is in this method.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue38584>
_______________________________________


More information about the Python-bugs-list mailing list