Search code examples
pythonargparse

How do I create an optional argument that is an alias of another argument with a certain value?


I need to edit a Python 3 program, let's call it ./foo, that uses argeparse to parse its argument list.

Currently, this program allows one to specify an optional input file on the command line. If it is not specified, then foo reads the file setting.txt

$ ./foo 
$ ./foo --input my_settings.txt

The code that does this pretty simple:

parser.add_argument(
    '--input',
    default='settings.txt'
)

The intent was to give personalized settings, but in practice, 99% of people who use the --input argument specify one particular file other_settings.txt. I'd like to add a mutually exclusive convenience argument, --common that is equivalent to the --input other_settings.txt

# These are the same.
$ ./foo --input other_settings.txt
$ $ ./foo --common

What is the recommended way to accomplish this? For example, should I have both arguments write to the same dest value? Do I have them write to separate destinations and then add some logic inside the body of the code, similar as was done here?


Solution

  • The solution was to create a mutually exclusive argument group grp. I added two arguments to the group in this order:

    1. The original argument
    2. A new argument with
    grp.add_argument(
        '--input',
        default='settings.txt'
    )
    grp.add_argument(
            "--common",
            action="store_const",
            dest="input",
            const="other_settings.txt",
        )
    

    This order seems to ensure that the value that is provided when neither of them are specified is settings.txt