7

I have a function where, based on different case, I'm changing the parameters sent to a function whose result I'm returning. I would like to just decide parameters in the middle of the method, and only have one return call at the bottom of my function. Please be aware this is not what my code looks like, it's just an example. I'm using Django, if that's relevant.

if x:
    return func(param1, param2, param3)
elif y:
    return func(param4, param5, param6)
elif z:
    return func(param7, param8, param9)

I would like this to read

if x:
    parameters = (param1, param2, param3)
elif y:
    parameters = (param4, param5, param6)
elif z:
    parameters = (param7, param8, param9)
return func(parameters)

Thanks for the help!

4 Answers 4

5

Use * to unpack the parameter tuple:

func(*parameters)

Demo:

def func(x,y,z):
     print x,y,z
>>> params = (1,2,3)
>>> func(*params)
1 2 3
>>> params = (4,5,6)
>>> func(*params)
4 5 6
4

Just do

return func(*parameters)

It unpacks the parameters and passes it to the func. Read the Python Docs entry on this.

For example -

>>> def test(a, b, c):
        print a, b, c


>>> testList = [2, 3, 4]
>>> test(*testList)
2 3 4

Your code would now read -

if x:
    parameters = (param1, param2, param3)
elif y:
    parameters = (param4, param5, param6)
elif z:
    parameters = (param7, param8, param9)
return func(*parameters)
0
1

There's a pythonic approach to this that's kind of pretty:

paramDictionary = { x : (param 1, param 2, param 3), y : (...), z:(...) }
return func( *paramDictionary[ indicator ] )

This tends to be neater code in python. You're still using the * to unpack your variables, but you don't need rambling lines of if statements!

0

Can you not simply do

return func(parameters[0], parameters[1], parameters[2])

?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.