Is there a way to create a python function from a string? For example, I have the following expression as a string:
dSdt = "-1* beta * s * i"
I've found a way to tokenize it:
>>> import re
>>> re.findall(r"(\b\w*[\.]?\w+\b|[\(\)\+\*\-\/])", dSdt)
['-', '1', '*', 'beta', '*', 's', '*', 'i']
And now I want to (somehow - and this is the part I don't know) convert it to something with the same behavior as:
def dSdt(beta, s, i):
return -1*beta*s*i
I've thought about something like eval(dSdt)
, but I want it to be more general (the parameters beta
, s
and i
would have to be known to exist ahead of time).
Some close requests have linked to this question for evaluating a mathematical expression in a string. This is not quite the same as this question, as I'm looking to define a function from that string.