How to pass two or three parameters to a function?

Viewed 263

This is maybe a little different than just the traditional *args **kwargs paradigm:

I have a mathematical function that takes three independent parameters as input, however, it can also be solved (non-compactly) by specifying any two of the three.

Currently, I have the non-compact solution based strictly on a and b, with c as an optional constraint:

def func(a,b,c=None):
  if c is not None:
    # do something with a, b, and c
  else:
    # do something with only a, b
  return result

However, I would like to be able to specify any two of a, b, or c, and still keep the option of specifying all three. What's the most Pythonic way of doing that?

2 Answers

You can just give them all default values of None, then pass the arguments as keyword arguments:

def foo(a=None, b=None, c=None):
    print(a, b, c)

foo(a=123, b=456)
foo(a=123, c=789)
foo(b=456, c=789)

This example produces:

123 456 None
123 None 789
None 456 789

Alternative approach:

def func(**kwargs):
    p_keys = kwargs.keys()
    if 'a' in p_keys and 'b' in p_keys:
        # non-compact solution
        if 'c' in p_keys:
            # apply optional constraint
    elif set(p_keys).issubset({'a', 'b', 'c'}):
        # apply solution for 'any two'
    else:
        #complain loudly
        pass
    return
Related