When using argparse
, I've not found an elegant/DRY way to use the function/method defaults instead of the defaults passed by argparse.
For example, I have foreign code I am loathe to modify. How do I tell argparse
(or elegantly handle after argparse
) to use the function defaults if the user does not pass in a clear preference on the command-line?
import argparse
def foreign_func(fav_color="blue"):
print(fav_color)
clparser = argparse.ArgumentParser()
clparser.add_argument(
"--color",
default=None,
help="Enter color")
clargs = clparser.parse_args()
foreign_func(fav_color=clargs.color)
This will print 'None', instead of "blue"
My default approach is something like:
if clparser.color:
foreign_func(fav_color=clargs.color)
else:
foreign_func()
but this seems clunky, especially if there are multiple command-line options.
EDIT: Hi folks, thank you for the fast feedback. To clarify, although it would be nice for argparse to display 'blue' in it's help, that's not my goal.
I'm looking for:
my_prog --color=red
>>> red
my_prog
>>> blue
With the code above, the program is outputting 'None', not "blue"