I might tackling this completely wrong, but I am curious if this can be done in Python.
I am trying to built a function that takes a string and returns a function based on that string. For instance, given b*exp(a*x)
and a list of inputs ['a','b','c']
is there a way to create this function dynamically in Python?
def f_fast(a, b, x):
return b*np.exp(a*x)
I can see how I could create a slow version of that using eval
:
np_funcs = {'exp':np.exp, 'sin':np.sin, 'cos':np.cos}
def make_func(s, vars):
def f(*x):
d = {e:x[i] for i, e in enumerate(vars)}
values = dict(d.items() + np_funcs.items())
return eval(s, {"__builtins__": None}, values)
return f
s = 'b*exp(a*x)'
f = make_func(s, ['a', 'b', 'x'])
But this function will do string evaluation of every call. I wonder if there is a way to do the translation of string into functions only at creation and then subsequent calls will be fast.
Currently this implementation is very slow:
x = np.linspace(0,1,10)
print timeit.timeit('f(1,2,x)', "from __main__ import f, x, f_fast", number=10000)
print timeit.timeit('f_fast(1,2,x)', "from __main__ import f, x, f_fast", number=10000)
returns
0.16757759497
0.0262638996569
Any help, including explaining why this can't be done or why it is a stupid approach, would be greatly appreciated.
Thank you in advance.