Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing Python function parameters as a variable to call later

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!

like image 596
Brandon Avatar asked Jul 08 '13 17:07

Brandon


1 Answers

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
like image 116
Ashwini Chaudhary Avatar answered Sep 20 '22 18:09

Ashwini Chaudhary