If I have an optional argument with optional argument value, is there a way to validate if the argument is set when the value is not given?
For instance:
parser = argparse.ArgumentParser()
parser.add_argument('--abc', nargs='?')
args = parser.parse_args()
Would correctly give me:
optional arguments:
--abc [ABC]
How do I distinguish between 1 and 2 below?
- '' => args.abc is None
- '--abc' => args.abc is still None
- '--abc something' => args.abc is something
...
Update:
Found a trick to solve this problem: you can use "nargs='*'" instead of "nargs='?'". This way #1 would return None, and #2 would return an empty list. The downside is this will allow multiple values for the arguments to be accepted too; so you'd need to add a check for it if appropriate.
Alternatively you can also set a default value for the argument; see answer from chepner and Anand S Kumar.
With
nargs='?'
, you can supply both adefault
andconst
.If the argument is not given it uses the default:
If given, but without an argument string, it uses the const:
Otherwise it uses the argument string:
Not sure if this is the standard way, but you can set
default
argument to something , and then that value would be used in case--abc
is not in the argument list.Example code -
Result -
Use a different default value for the option. Compare
I'm not sure how you would provide a different value for when
--abc
is used without an argument, short of using a custom action instead of thenargs
argument.