Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 argparse set_defaults doesn't take string as option name?

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.

like image 464
Quantum Mechanic Avatar asked Aug 09 '26 18:08

Quantum Mechanic


2 Answers

You can use dictionary expansion:

parser.set_defaults(**{NUM: ONE})
like image 57
Daniel Roseman Avatar answered Aug 12 '26 09:08

Daniel Roseman


You can use the argparse's default argument to do that:

pform.add_argument('--'+opt, dest=NUM, action='store_const', const=opt, default=NUM)
like image 36
coder Avatar answered Aug 12 '26 09:08

coder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!