1

I am using argparse in Python 3. My requirement is to support the following 3 use-cases:

$ python3 foo.py --test       <== results e.g. in True
$ python3 foo.py --test=foo   <== results in foo
$ python3 foo.py              <== results in arg.test is None or False

I found store_true, and store, but can't find any configuration where I can achieve the following arg list as mentioned above. Either it wants to have a parameter, or None. Both seems not to work. Is there any way to make a argument optional?

Daniel Stephens
  • 2,371
  • 8
  • 34
  • 86
  • 1
    Don't understand *results*, and what is different between 1&3 ? – azro Apr 27 '20 at 21:20
  • 2
    `nargs='?'` marks the argument as optional. The example given in [the nargs examples[](https://docs.python.org/3/library/argparse.html#nargs) seems to match what you're attempting to do - as soon as you clear up the confusion about example 1 & 3. – MatsLindh Apr 27 '20 at 21:22
  • 2
    `nargs='?'` plus `default` and `const` values should do the trick. – hpaulj Apr 27 '20 at 21:55

1 Answers1

2

Use nargs='?' to make the argument optional, const=True for when the flag is given with no argument, and default=False for when the flag is not given.

Here's the explanation and an example from the documentation on 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. Some examples to illustrate this:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs='?', const='c', default='d')
>>> parser.add_argument('bar', nargs='?', default='d')
>>> parser.parse_args(['XX', '--foo', 'YY'])
Namespace(bar='XX', foo='YY')
>>> parser.parse_args(['XX', '--foo'])
Namespace(bar='XX', foo='c')
>>> parser.parse_args([])
Namespace(bar='d', foo='d')
wjandrea
  • 28,235
  • 9
  • 60
  • 81