Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing parameter as keyword to new function

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading