Skip to content Skip to sidebar Skip to footer

Can I Check If A Value Was Supplied By The Default Or By The User?

Is there a way, when using argparse, to tell whether a field has a value because the user specified it or because it was not specified and got the default value? Note: I would also

Solution 1:

Don't specify a default value if it's just complicating things:

parser.add_argument('-p', '--path', 
                    help="The path to a file to read")

And then later on in your code:

if args.path:
    # user specify a value for path# using -ppasselif cfg.path:
    # user provided a path in the configuration value
    args.path = cfg.path
else:
    # no value was specified, use some sort of default value
    args.path = DEFAULT_PATH

Or, more compactly:

args.path = next(valforvalin 
                 [args.path, cfg.path, DEFAULT_PATH]
                 ifvalis not None)

This assumes that cfg.path will be None if no path was specified in the config file. So if cfg is actually a dictionary, cfg.get('path') would do the right thing.

And just for kicks, here's a terrible idea that can tell the difference between using a default value and explicit specifying a value that is the same as the default:

import argparse

classDefault(object):
    def__init__(self, value):
        self.value = value

    def__str__(self):
        returnstr(self.value)

DEFAULT_PATH = Default('/some/path')

defparse_args():
    p = argparse.ArgumentParser()
    p.add_argument('--path', '-p',
                   default=DEFAULT_PATH)
    return p.parse_args()

defmain():
    args = parse_args()

    if args.path is DEFAULT_PATH:
        print'USING DEFAULT'else:
        print'USING EXPLICIT'print args.path

if __name__ == '__main__':
    main()

Note that I don't actually think this is a good idea.

Post a Comment for "Can I Check If A Value Was Supplied By The Default Or By The User?"