Check if argparse optional argument is set or not

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:

        #do something
        #do something else

Does this work the same for float / int / string type arguments?

I could set a default parameter and check it (e.g., set myArg = -1, or "" for a string, or "NOT_SET"). However, the value I ultimately want to use is only calculated later in the script. So I would be setting it to -1 as a default, and then updating it to something else later. This seems a little clumsy in comparison with simply checking if the value was set by the user.

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 as ap

    def main():
        parser = ap.ArgumentParser(description="My Script")
        args, leftovers = parser.parse_known_args()

        if args.myArg is not None:
            print "myArg has been set (value is %s)" % args.myArg