1

Let's say the user types:

./args.py --create --mem 5

and my parser looks like this:

parser.add_argument('--create', nargs='*', default=None)

Normally --create takes a list with nargs='*', however in this case the user passed nothing.

What I would like to happen is that --create is set to the default value when invoked, instead I get []

Question: Is there anyway to detect if --create shows up in the command line arguments without anything after it?

SurpriseDog
  • 462
  • 8
  • 18
  • `create` is set to a list of the strings that follow. WIth '*', that list may be empty, `[]`. – hpaulj Sep 14 '21 at 22:12
  • The trick is that `create = default` when not passed and `create = []` when passed without anything following. I was expecting the other way around. – SurpriseDog Sep 14 '21 at 22:33
  • So now my code is looking for `[]` instead of the default value. – SurpriseDog Sep 14 '21 at 22:37
  • Default for a `positional` with `nargs='*' is extra tricky, since 'nothing' satisfies its requirements.. It is always seen, even when there aren't any strings. – hpaulj Sep 14 '21 at 23:16

1 Answers1

2

Here is a simple code snippet:

import argparse


parser = argparse.ArgumentParser()
parser.add_argument('--create', nargs='*', default=None)
options = parser.parse_args()
print(options)

Here are a few interactions:

$ ./args.py 
Namespace(create=None)

$ ./args.py --create
Namespace(create=[])

$ ./args.py --create one
Namespace(create=['one'])

$ ./args.py --create one two
Namespace(create=['one', 'two'])

As you can see, if the user does not add the --create flag, it is None. If the user use --create flag with nothing, you get an empty list.

Hai Vu
  • 37,849
  • 11
  • 66
  • 93