
Instead of eval in __call__ we may build a
(lambda) function
class StringFunction:
def _build_lambda(self):
s = 'lambda ' + ', '.join(self._var)
# add parameters as keyword arguments:
if self._prms:
s += ', ' + ', '.join(['%s=%s' % (k, self._prms[k]) \
for k in self._prms])
s += ': ' + self._f
self.__call__ = eval(s, self._globals)
| |
For a call
f = StringFunction('A*sin(x)*exp(-b*t)', A=0.1, b=1,
independent_variables=('x','t'))
the s looks like
lambda x, t, A=0.1, b=1: return A*sin(x)*exp(-b*t) |