Passing parameter as keyword to new function

Question:

Say I have the following code:

def my_func(a, b, param="foo"):
    if param == "foo":
        obj = other_func(foo=(a, b))
    elif param == "bar":
        obj = other_func(bar=(a, b))
    elif param == "test":
        obj = other_func(test=(a, b))

Is there a more pythonic way to convert the argument into a keyword for a new function? This method gets tedious after a few if statements. Something like this would be better (just example):

def my_func(a, b, param="foo"):
    obj = other_func(param=(a, b))

After plenty of testing, the best I have found is the following:

def my_func(a, b, param="foo"):
    temp_str = f"{param}=(a, b)"
    obj = eval("other_func("+temp_str+")")

But I have only heard bad things about eval(), which I don’t fully understand.

Asked By: AuraZz

||

Answers:

Use the ** operator to unpack a dict and pass its items as keyword arguments to a function:

def my_func(a, b, param="foo"):
    obj = other_func(**{param: (a,b)})
Answered By: John Gordon
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.