Author paul.j3
Recipients John.Didion, bethard, manveru, paul.j3, xuanji
Date 2014-09-03.20:58:56
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1409777937.18.0.614599529823.issue11588@psf.upfronthosting.co.za>
In-reply-to
Content
http://stackoverflow.com/questions/25626109/python-argparse-conditionally-required-arguments

asks about implementing a 'conditionally-required-arguments' case in `argparse`.  The post-parsing test is simple enough:

    if args.argument and (args.a is None or args.b is None):
        # raise argparse error here

I believe the clearest and shortest expression using Groups is:

    p = ArgumentParser(formatter_class=UsageGroupHelpFormatter)
    g1 = p.add_usage_group(kind='nand', dest='nand1')
    g1.add_argument('--arg', metavar='C')
    g11 = g1.add_usage_group(kind='nand', dest='nand2')
    g11.add_argument('-a')
    g11.add_argument('-b')

The usage is (using !() to mark a 'nand' test):

    usage: issue25626109.py [-h] !(--arg C & !(-a A & -b B))

This uses a 'nand' group, with a 'not-all' test (False if all its actions are present, True otherwise).
History
Date User Action Args
2014-09-03 20:58:57paul.j3setrecipients: + paul.j3, bethard, xuanji, John.Didion, manveru
2014-09-03 20:58:57paul.j3setmessageid: <1409777937.18.0.614599529823.issue11588@psf.upfronthosting.co.za>
2014-09-03 20:58:57paul.j3linkissue11588 messages
2014-09-03 20:58:56paul.j3create