0

I would like to make one argument be required or not depending on the value of another argument supplied. Here is what I tried

import argparse

argparser = argparse.ArgumentParser()

#instead of hard coding it to always be required like this
#argparser.add_argument('-n', '--name', help='Name', required=True)
#I tried to use a boolean condition in the argparse configuration
argparser.add_argument('-n', '--name', help='Name', required=(not empty))
argparser.add_argument('-e', '--empty', help='Empty execution', action="store_true")

args = argparser.parse_args();

empty = args.empty
name = args.name

this does not work. Of course, I can write my own input validation check as a workaround but I would prefer to do it using the conventional notation, if possible.

Can argparse argument requirement be conditional on other arguments through the canonical API?

amphibient
  • 29,770
  • 54
  • 146
  • 240
  • In this case you want mutually exclusive flags, yes? – erip Nov 18 '16 at 19:10
  • If so, there's a [question](http://stackoverflow.com/questions/17909294/python-argparse-mutual-exclusive-group) already. – erip Nov 18 '16 at 19:11
  • 1
    No. We've discussed work arounds, but there's nothing built in. While there is a `mutually-exclusive` tool, there isn't a mutually-inclusive one. – hpaulj Nov 18 '16 at 19:12
  • 1
    No. The way to do this is code after the `.parse_args()` call to validate whatever invariants you want to apply. – twalberg Nov 18 '16 at 19:47
  • it would be a nice addition to the argparse API to be able to do this though. just another wish list item... – amphibient Nov 18 '16 at 19:53
  • I've worked on a patch for a bug/issue that seeks nested inclusive arguments. Doing the test is trivial, but making a nice API is more work. Especially producing a meaningful `usage`. No one seems to think about how they would instruct their users. – hpaulj Nov 18 '16 at 21:03

0 Answers0