Is there a way pass arguments conditionally in Python (I use Python 2.7)?
As an example, this code gives 2 or 3 arguments depending if the 3rd argument exists in a dictionary.
if "arg3" in my_dict:
my_method(
my_dict[arg1],
my_dict[arg2],
my_dict[arg3],
)
else:
my_method(
my_dict[arg1],
my_dict[arg2],
)
I think it looks redundant to write it this way. I've seen some info on argparse
, which I think would look like this:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(my_dict[arg1])
parser.add_argument(my_dict[arg2])
if arg3 in my_dict:
parser.add_argument(my_dict[arg3])
args = parser.parse_args()
my_method(args)
I don't really like this method either, as it needs an import and is hard to read.
Is there a way to do something like:
my_method(
my_dict[arg1],
my_dict[arg2],
my_dict[arg3] if arg3 in my_dict,
)
Or any other way I am missing, that would be simple and clean?