I am working with the argparse
library in python. At some time, I use an argument called param
that takes 2 args: a key and a value. The line of code I use is the following:
parser.add_argument("-p", "--param", nargs=2, action="append",
help="key and value for query",
type=str, metavar="key value"
)
What's wrong here is when I call the help, it displays like this:
optional arguments:
-h, --help show this help message and exit
-p key value key value, --param key value key value
key and value for query parameters
The name 'key value' is repeated twice. I tried with lists, and generators but the only way i found was creating a little class containing the different values and yielding them when ask to __str__
like this:
class Meta:
def __init__(self, iterable):
self.gene = itertools.cycle(iterable)
def __str__(self):
return self.gene.__next__()
and I call add_argument
like this:
parser.add_argument("-p", "--param", nargs=2, action="append",
help="key and value for query parameters",
type=str, metavar=Meta(["key", "value"])
)
And it displays correctly:
-p key value, --param key value
key and value for query parameters
But I find pretty ugly using a temporary class like Meta
, and I feel like there must be another (better) way of doing this. Am I doing it right ?
From scrolling the doc deeply, I've found my answer
Different values of nargs may cause the metavar to be used multiple times. Providing a tuple to metavar specifies a different display for each of the arguments:
indeed, this works perfectly fine:
parser.add_argument("-p", "--param", nargs=2, action="append",
help="key and value for query parameters",
type=str, metavar=("key", "value")
)