Search code examples
pythonargparse

Python Argparse - Set default value of a parameter to another parameter


I've added a parameter -c, now I want to add another parameter called -ca. How can I set the default value of -ca as -c? What I want to do is if -ca is not specified, assign -c to -ca.

parser.add_argument("-c", type=str)

parser.add_argument("-ca", type=str, default=XXX)

Solution

  • Normally, single dash flags are single characters. So -ca is unwise, though not illegal. In normal POSIX practice it could be interpreted as -c a or -c -a.

    Also argparse allows flagged arguments (optionals) to occur in any order.

    Parsing starts out by assigning all the defaults. When the relevant flag is encountered, the new value overwrites the default. Given that order, it's impossible for one argument to take on the value of another as a default.

    In general interactions between arguments are best handled after parsing. There is a mutually_exclusive grouping, but no mutually_inclusive. You can build in some sort of interaction via custom Action classes, but implementing that is just as much work as any post-parsing testing.

    In sum, the simplest thing is to use the default default, None, and test

    if args.ca is None:
        args.ca = args.c