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

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

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?

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

>Solution :

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}.

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