Reputation: 107
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?
Upvotes: 3
Views: 1348
Reputation: 21643
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
Upvotes: 0
Reputation: 24052
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
Upvotes: 3