You can do this with nargs='?':
One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced. Note that for optional arguments, there is an additional case - the option string is present but not followed by a command-line argument. In this case the value from const will be produced.
Your three cases would give:
- The
default value; - The
const value; and '~/some/path'
respectively. For example, given the following simple implementation:
from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('-t', nargs='?', default='not present', const='present without value') print(parser.parse_args().t)
You'd get this output:
$ python test.py not present $ python test.py -t present without value $ python test.py -t 'passed a value' passed a value