Oliver
Oliver

Reputation: 3682

argparse set default to multiple args

I want use argparse to specify a option that take three integer values: like specifying a range: start, end, step.

parser.add_argument('--range', nargs=3, metavar=('start', 'end', 'step'), 
             type=int, help="specify a range')

However, it is not clear to me how to provide default values to all three values. Do I need to define it as string and parse it myself?

Upvotes: 19

Views: 20083

Answers (2)

Robᵩ
Robᵩ

Reputation: 168616

Does this work for you?

parser.add_argument('--range', default=[4,3,2], 
                    nargs=3, metavar=('start', 'end', 'step'),
                    type=int, help='specify a range')

Demo program:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--range', default=[4,3,2], nargs=3, metavar=('start', 'end', 'step'),
             type=int, help='specify a range')
print parser.parse_args([])

# prints Namespace(range=[4, 3, 2])

Upvotes: 23

Air
Air

Reputation: 8595

When using nargs, to provide multiple default values, define them in a list - see the third code snippet of this section of the docs, which contains the following example:

parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')

Upvotes: 7

Related Questions