Saving Python function parameters as a variable to call later

I have a function where, depending on another case, I change the parameters sent to the function whose result I return. I would just like to define the parameters in the middle of the method and have only one callback at the bottom of my function. Keep in mind that this is not what my code looks like, this is just an example. I use Django if it is relevant.

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

I wish it 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!

+6
source share
4 answers

Use * to unpack a tuple of parameters :

 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
source

Just do

return func(*parameters)

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

For instance -

 >>> def test(a, b, c): print a, b, c >>> testList = [2, 3, 4] >>> test(*testList) 2 3 4 

Now your code will read -

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

There is a pythonic approach to such a good one:

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

This is usually cleaner code in python. You still use * to unpack your variables, but you don't need linear lines of if statements.

+1
source

Can't you just do

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

?

0
source

Source: https://habr.com/ru/post/948966/


All Articles