Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable argparse choices message

Argparse displays message about the list of choices, like in this example:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--styles', choices=long_list_of_styles)

As I'm passing a long list, help message does not look good, in fact it looks confusing and it shadows other arguments by its presence, because of all those choices being printed.

Is there any way to tell Argparser not to print arguments choices?

like image 676
vedar Avatar asked Oct 17 '25 12:10

vedar


1 Answers

The proposed duplicate, Python's argparse choices constrained printing presents a relatively complicated solution - a custom HelpFormatter. Or a custom type.

A higher vote question/answers is Python argparse: Lots of choices results in ugly help output

You'll find more with a [argparse] choices search.

The simplest solution is to set the metavar parameter. None displays nothing in the choices slot, but you probably want a short word

In [8]: styles=['one','two','three','four']
In [10]: parser = argparse.ArgumentParser()
In [11]: parser.add_argument('--styles', metavar='STYLE', choices=styles,
    ...:    help='list of choices: {%(choices)s}')
Out[11]: _StoreAction(option_strings=['--styles'], dest='styles', nargs=None, const=None, default=None, type=None, choices=['one', 'two', 'three', 'four'], help='list of choices: {%(choices)s}', metavar='STYLE')

In [12]: parser.print_help()
usage: ipython3 [-h] [--styles STYLE]

optional arguments:
  -h, --help      show this help message and exit
  --styles STYLE  list of choices: {one, two, three, four}

I included %(choices)s in the help to list them there. You could of course put your own summary there. A long list fits better there than in usage.

like image 116
hpaulj Avatar answered Oct 19 '25 01:10

hpaulj