python – Check if argparse optional argument is set or not
python – Check if argparse optional argument is set or not
I think that optional arguments (specified with --
) are initialized to None
if they are not supplied. So you can test with is not None
. Try the example below:
import argparse
def main():
parser = argparse.ArgumentParser(description=My Script)
parser.add_argument(--myArg)
args, leftovers = parser.parse_known_args()
if args.myArg is not None:
print myArg has been set (value is %s) % args.myArg
As @Honza notes is None
is a good test. Its the default default
, and the user cant give you a string that duplicates it.
You can specify another default=mydefaultvalue
, and test for that. But what if the user specifies that string? Does that count as setting or not?
You can also specify default=argparse.SUPPRESS
. Then if the user does not use the argument, it will not appear in the args
namespace. But testing that might be more complicated:
parser.add_argument(--foo, default=argparse.SUPPRESS)
# ...
args.foo # raises an AttributeError
hasattr(args, foo) # returns False
getattr(args, foo, other) # returns other
Internally the parser
keeps a list of seen_actions
, and uses it for required and mutually_exclusive testing. But it isnt available to you out side of parse_args
.
python – Check if argparse optional argument is set or not
I think using the option default=argparse.SUPPRESS
makes most sense. Then, instead of checking if the argument is not None
, one checks if the argument is in
the resulting namespace.
Example:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(--foo, default=argparse.SUPPRESS)
ns = parser.parse_args()
print(Parsed arguments: {}.format(ns))
print(foo in namespace?: {}.format(foo in ns))
Usage:
$ python argparse_test.py --foo 1
Parsed arguments: Namespace(foo=1)
foo in namespace?: True
Argument is not supplied:
$ python argparse_test.py
Parsed arguments: Namespace()
foo in namespace?: False