I have the following code repeated over and over again:
def foo(data):
result = (0, 0, 0)
var1, var2, var3 = init_variables(data)
for i in xrange(var1):
result[0] += variable_func_1(data, var2, var3)
result[1] += variable_func_2(data, var3)
result[2] += fixed_func()
return result
Across all repetitions everything is fixed except for variable_func_n which can take a variable number of arguments, the number of these functions also varies.
I'd like to factor out the common code across all these functions so the first thing that comes to mind is to make use of higher order functions like so:
def foo(data, func_list):
var1, var2, var3 = init_variables(data)
results = (len(func_list) + 1) * [0]
for i in xrange(var1):
for j, func in enumerate(func_list):
results[j] += (func(data, var1, var2, var3))
results[len(func_list)] += fixed_func()
return results
The problem with this solution is that it requires me to modify the signature of all the varying functions such that they can take more parameters. Is there a cleaner solution that wouldn't require me to modify the signature of all the passed in functions?
variable_func_1(data, var2, var3)and notvariable_func_1(data, var3, var2)? If there is no such rule, then I believe what you are asking for is not possible. Eveninspectcannot tell which value should go to which position.inspectis probably going to be the best solution without refactoring I imagine.