Conditional passing of arguments to methods in python
Question: I have many possible arguments from argparse that I want to pass to a
function. If the variable hasn't been set, I want the method to use its
default variable. However, handling which arguments have been set and which
haven't is tedious:

    
    
    import argparse
    def my_func(a = 1, b = 2):
      return a+b
    
    if __name__ == "__main__":
        parser = argparse.ArgumentParser(description='Get the numeric values.')
        parser.add_argument('-a', type=int)
        parser.add_argument('-b', type=int)
        args = parser.parse_args()
    
        if not args.a is None and not args.b is None:
            result = my_func(a = args.a, b = args.b)
        elif not args.a is None and args.b is None:
            result = my_func(a = args.a)
        elif not args.b is None and args.a is None:
            result = my_func(b = args.b)
        else:
            result = my_func()
    

It seems like I should be able to do something like this:

    
    
    result = my_func(a = args.a if not args.a is None, b = args.b if not args.b is None)
    

But this gives a syntax error on the comma.

I could set default values in the argparser, but I want to use the defaults
set in the method definition.


Answer: Use a dictionary with the kwargs unpacking syntax.

    
    
    args = parser.parse_args()
    result = my_func(**vars(args))
    

**Edit**

Use the `SUPPRESS` argument to ArgumentParser to remove empty values:

    
    
    parser = argparse.ArgumentParser(description='Get the numeric values.',
                                     argument_default=argparse.SUPPRESS)
    

