Rectangle 27 0

Python argparse: nargs + or * depending on prior argument?

% --odas
If you are making a server query, you must pass an address.
% --odam
Namespace(address=['', ''], query_type='odam')
% --odam 1 2 3
Namespace(address=['1', '2', '3'], query_type='odam')
import argparse
import sys

class AddressAction(argparse.Action):
    def __call__(self, parser, args, values, option = None):
        if args.query_type=='odam' and not args.address:
        if not args.address:
            parser.error("If you are making a server query, you must pass an address.")

p = argparse.ArgumentParser()
g = p.add_mutually_exclusive_group(required=True)
g.add_argument('--odam', dest='query_type', action='store_const',
        const='odam', help="Odamex Master query.")
g.add_argument('--odas', dest='query_type', action='store_const',
        const='odas', help="Odamex Server query.")
p.add_argument('address', nargs='*', action=AddressAction)
args = p.parse_args()

One downside of using a custom action is that the action is called when the argument is parsed, and arguments after the one in question have not yet been added to the values array. This makes optional arguments sensitive to order. To avoid this, dont add a custom action, just check the dependency after the main call to parse_args, and call p.error('explanation message') if the dependecy fails. This prints out the help text and exits.

Precisely what I was looking for!

You can do this with an custom argparse.Action: