python / cpython

The Python programming language
https://www.python.org/
Other
61.16k stars 29.52k forks source link

HelpFormatter does not properly consider extra indentation from subparsers when printing arguments #119021

Open mathgeniuszach opened 2 months ago

mathgeniuszach commented 2 months ago

Bug report

Bug description:

Consider the following code,

import argparse
parser = argparse.ArgumentParser(prog="prog")
subparsers = parser.add_subparsers(metavar="mode")
a = subparsers.add_parser("option-a-here", help="helpful help")
b = subparsers.add_parser("option-b-here", help="super helpful help")
parser.parse_args()

Which produces this output, where even though there is more than enough room to print the descriptions after the arguments, it places them on the next line instead.

usage: prog [-h] mode ...

positional arguments:
  mode
    option-a-here
                 helpful help
    option-b-here
                 super helpful help

options:
  -h, --help     show this help message and exit

While with this code instead,

import argparse
parser = argparse.ArgumentParser(prog="prog")
parser.add_argument("--option-a", help="helpful help")
parser.add_argument("--option-b", help="super helpful help")
parser.parse_args()

The program correctly places them on the same line:

usage: prog [-h] [--option-a OPTION_A] [--option-b OPTION_B]

options:
  -h, --help           show this help message and exit
  --option-a OPTION_A  helpful help
  --option-b OPTION_B  super helpful help

I believe this is an error with HelpFormatter.add_argument(), where the indent/dedent coming from HelpFormatter._iter_indented_subactions() is neither evaluated by _SubParserAction._get_subactions() nor considered by self._current_indent.

CPython versions tested on:

3.11, 3.12, 3.13

Operating systems tested on:

Linux

Linked PRs

olgarithms commented 1 month ago

I'd like to work on this!