Home > OS >  Passing parameter as keyword to new function
Passing parameter as keyword to new function

Time:08-21

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.

CodePudding user response:

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)})
  • Related