python 2.7 - Functions as values in a dictionary being iterated instead of being selected -


i have function looks similar this:

def some_function(self, case, index):     threading.lock:         return{             'case1':function1(index),             'case2':function2(index)         }[case] 

and elsewhere function being called such:

for in range(4)     self.module.some_function('case1', i) 

which should iterate function1 indices within specified range. instead, both function1 , function2 iterated indices. there problem implementation above? causing both function1 , function2 called when single key given?

indeed, dict literal expression evaluated first:

{     'case1':function1(index),     'case2':function2(index) } 

and key specify after it, selected it, @ time 2 functions have executed.

so, should differently: first correct function must selected using case variable, , after selection function should executed passing argument it.

there several solutions, here one:

return [function1, function2][case == 'case2'](index) 

or dict literal:

return {     'case1': function1,      'case2': function2 }[case](index) 

or inline if:

return function1(index) if case == 'case1' else function2(index) 

or avoiding repetition of (index):

return (function1 if case == 'case1' else function2)(index) 

or can use plain if:

if case == 'case1':     return function1(index) return function2(index) 

Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -