Varad
Varad

Reputation: 1022

Is there a way to identify default value given by the argparse function ( I am using mutually exclusive option)

Right now I have used default value for mutually_exclusive option for certain parameters for my command line arguments using argparse/configargparse module.

The issue here is, if I pass a value on command line I argparse/configargparse fetches the value for the argument. However, when I don't pass a value in command line the parameter gets a default value returned by argparse/configargparse.

Now I need to identify from with in a program whether the value for the parameter is a command line parsed value or a default value assigned from argparse/configargparse.

Below is a sample code using the suggestion provided by one of the answers. When I run the below code

Case 1: python <file.py> --replace. 
       I am passing from command line.
       so the if loop where i set the default value is not 

getting executed

    Case 2: python file.py
            I am not passing any  argument here. 
By default "False" is set for "args.replace" and it doesn't go inside the if loop condition  where I am setting up the default value.

"Code"

from argparse import ArgumentParser


if __name__ == "__main__":
    myarg_sentinel = object()
    myarg_default = "True"  # The real default

    myarg_sentinel_1 = object()
    myarg_default_1 = "True"  # The real default

    p = ArgumentParser()
    p.add_argument('--myarg', default=myarg_sentinel)
    replace_parser = p.add_mutually_exclusive_group()

    replace_parser.add_argument(
        '--replace', help='Replace during import',
        dest='replace', action='store_true')
    replace_parser.add_argument(
        '--no-replace', help='Do not replace import',
        dest='replace', action='store_false', default=myarg_sentinel_1)

    args = p.parse_args()
    if args.myarg is myarg_sentinel:
        print "----I am setting default val here."
        args.myarg = myarg_default

    print args.replace

    if args.replace is myarg_sentinel_1:
        print "I am setting default val here.----"
        args.replace = myarg_default_1
    print args.myarg, args.replace

Upvotes: 1

Views: 481

Answers (1)

chepner
chepner

Reputation: 532003

Create a unique sentinel value to use as the default, then compare the value actually received to the sentinel.

myarg_sentinel = object()
myarg_default = ...  # The real default
p = ArgumentParser()
p.add_argument('--myarg', default=myarg_sentinel)
args = p.parse_args()
if args.myarg is myarg_sentinel:
    # Option not specified on the command line
    args.myarg = myarg_default

Upvotes: 1

Related Questions