I would like to check whether an optional argparse argument has been set by the user or not.
Can I safely check using isset?
Something like this:
<
Very simple, after defining args variable by 'args = parser.parse_args()' it contains all data of args subset variables too. To check if a variable is set or no assuming the 'action="store_true" is used...
if args.argument_name:
# do something
else:
# do something else
As @Honza notes is None
is a good test. It's the default default
, and the user can't 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:
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 isn't available to you out side of parse_args
.
You can check an optionally passed flag with store_true
and store_false
argument action options:
import argparse
argparser = argparse.ArgumentParser()
argparser.add_argument('-flag', dest='flag_exists', action='store_true')
print argparser.parse_args([])
# Namespace(flag_exists=False)
print argparser.parse_args(['-flag'])
# Namespace(flag_exists=True)
This way, you don't have to worry about checking by conditional is not None
. You simply check for True
or False
. Read more about these options in the docs here