I'm new to argparse, so this may be fundamental.
I prefer to have all of my string constants defined once (blah = 'foo'), and then use that throughout the code. When I get to set_defaults, it seems that I'm limited to kwarg-type parameters.
That is, parser.set_defaults(NUM=ONE) doesn't treat NUM as a string. Here's a fuller example:
ONE = 'one'
TWO = 'two'
SIX = 'six'
NUMBER_OPTS = [ONE, TWO, SIX]
NUM = 'num'
parser = argparse.ArgumentParser()
pform = parser.add_mutually_exclusive_group()
for opt in NUMBER_OPTS:
pform.add_argument('--'+opt, dest=NUM, action='store_const', const=opt)
parser.set_defaults(NUM=ONE) # Can't find a syntax to make this DWIM
args = parser.parse_args()
print("%s is %s" % (NUM, vars(args)[NUM]))
So while add_argument takes a string as a destination, set_defaults doesn't.
You can use dictionary expansion:
parser.set_defaults(**{NUM: ONE})
You can use the argparse's default argument to do that:
pform.add_argument('--'+opt, dest=NUM, action='store_const', const=opt, default=NUM)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With