Is there an elegant way to pass down an argument from function1() down to a function2(), that takes several arguments?

Question:

I have the following situation:

def func1(a = 0, b = 0):
    return a + b**2

def func2(x):
    if x == 'a':
        return func1(a = 2)
    elif x == 'b':
        return func2(b = 2)

print(func2('a'))

Is there a way to just pass a not as a String and get rid of the if statements?

Asked By: M Tomb

||

Answers:

Construct a dict and use that with the mapping unpacking syntax.

def func2(x):
    return func1(**{x: 2})

You might still want an if statement to verify that the value of x is the name of a valid parameter to func1. As shown here, a call like func2('c') will produce a TypeError when attempting to call func1 using {'c': 2}.

Answered By: chepner