I’ve defined a class that takes a list of the form [fname1,[parameters1],fname2,[parameters2],…] as parameter for the creation of an instance.
The idea is for the instance to execute all functions in the list at once, passing them their respective parameters – which works just fine as is, but the implementation I came up with is incredibly ugly.
It looks something like this:
# (The input list is split up and transformed into two lists -
# one containing the function names as strings, the other one containing tuples)
# (It then runs a for-loop containing the following statement)
exec '%s%s'%(fname[i],repr(parameter_tuple[i]))
Which outputs and runs ‘fname(parameters,more_parameters,and,so,on)’, just as it should do.
I don’t know why, but since I coded this, I consequently get the idea that I deserve a really good beating for it… although it works, I just know there has to be a less ugly implementation.
Anyone willing to help me see it? Or maybe to beat me up a bit? 😉
The simplest answer here, if you can do it, is to simply pass the functions rather than the function names, and then do a simple:
Note my use of
zip()to loop over two lists at once. This is the far more Pythonic option than looping over indices.Or, alternatively, use
itertools.starmap().If you truly cannot pass the functions directly, it becomes more difficult. For one, any solution relying on the names of variables will be inherently fragile, so the best option would be to create an explicit dictionary from function names to functions, then look up the function.
Otherwise, I would suggest using the
inspectmodule to find the functions you want. E.g:Produces:
Note, however, this is far less efficient and more roundabout. The best answer remains passing the functions themselves.