Harrison-O · GitHub

Bug report

When running a command line program with the --help/-h flag with argparse, if another flag has multiple names and choices to pick from, the options are printed multiple times instead of just once. For example, the program below:

import argparse
if __name__ == "__main__":
    parser = ArgumentParser()
    parser.add_argument('-m', '--metric', choices=["accuracy", "precision", "recall"])
    parser.parse_args(["-h"])

Will print

usage: argparse_test.py [-h] [-m {accuracy,precision,recall}]
options:
  -h, --help            show this help message and exit
  -m {accuracy,precision,recall}, --metric {accuracy,precision,recall}

Notice that the flag choices are printed out twice, once for each flag name. This is redundant and negatively impacts readability. The program should output:

usage: argparse_test.py [-h] [-m {accuracy,precision,recall}]
options:
  -h, --help            show this help message and exit
  -m, --metric {accuracy,precision,recall}

Your environment

  • CPython versions tested on: 3.10.6
  • Operating system and architecture: Windows 11 with WSL 2

Linked PRs

Read the original on github.com ↗