3

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?

3
  • 1
    For the distinction, you'd need them to be kwargs anyway, wouldn't you? So what's wrong with the **kwargs approach? Commented Nov 8, 2017 at 22:41
  • 3
    Give them all default values of None, then pass them as keyword arguments. Commented Nov 8, 2017 at 22:41
  • As far as your actual function block is concerned, you might want to do a try: [do something with a, b, and c, and then in the except block look at what exception is thrown and decide how to proceed from there. Commented Nov 8, 2017 at 22:50

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.