[New-bugs-announce] [issue45110] argparse repeats itself when formatting help metavars

Forest report at bugs.python.org
Sun Sep 5 22:18:58 EDT 2021

New submission from Forest <forestix at sonic.net>:

When argparse actions have multiple option strings and at least one argument, the default formatter presents them like this:

                        Perform a task with the given argument.
  -p STRING, --print STRING
                        Print the given string.

By repeating the metavars, the formatter wastes horizontal space, making the following side-effects more likely:

- The easy-to-read tabular format is undermined by overlapping text columns.
- An action and its description are split apart, onto separate lines.
- Fewer actions can fit on the screen at once.
- The user is presented with extra noise (repeat text) to read through.

I think the DRY principle is worth considering here. Help text would be cleaner, more compact, and easier to read if formatted like this:

  -t, --task ARGUMENT   Perform a task with the given argument.
  -p, --print STRING    Print the given string.

Obviously, actions with especially long option strings or metavars could still trigger line breaks, but they would be much less common and still easier to read without the repeat text.

I am aware of ArgumentParser's formatter_class option, but unfortunately, it is of little help here.  Since the default formatter class reserves every stage of its work as a private implementation detail, I cannot safely subclass it to get the behavior I want.  My choices are apparently to either re-implement an unreasonably large swath of its code in my own formatter class, or override the private _format_action_invocation() method in a subclass and risk future breakage (and still have to re-implement more code than is reasonable.)

Would it make sense to give HelpFormatter a "don't repeat yourself" option?  (For example, a boolean class attribute could be overridden by a subclass and would be a small change to the existing code.)

Alternatively, if nobody is attached to the current behavior, would it make sense to simply change HelpFormatter such that it never repeats itself?

components: Library (Lib)
messages: 401110
nosy: forest
priority: normal
severity: normal
status: open
title: argparse repeats itself when formatting help metavars
type: behavior
versions: Python 3.10, Python 3.11, Python 3.6, Python 3.7, Python 3.8, Python 3.9

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list