Cory
Cory

Reputation: 15615

Is it possible to set argparse's optional argument to a default value based on other optional argument?

I am using argparse and I have two optional arguments:

  parser.add_argument('-a', '--arg1', default=1, type=int)
  parser.add_argument('-b', '--arg2', action='store_true', default=False)

Is there a way to set arg1 default value of "1" if only if arg2 is set True?

In other word, I only want to do the following only if arg2 is set to True:

  parser.add_argument('-a', '--arg1', default=1, type=int)

Otherwise, it will be set to:

  parser.add_argument('-a', '--arg1', type=int)

Upvotes: 1

Views: 410

Answers (1)

hpaulj
hpaulj

Reputation: 231738

A test after parsing would be the simplest way to achieve this:

if args.arg2 and args.arg1 is None:
    args.arg1 = 1

You could put this sort of test in an custom Action. You have to take into consideration the order of occurance (or not). I haven't worked out the details, but I can't imagine it being any simpler than this post-parse test.

Upvotes: 2

Related Questions