I want to be able to take a string which describes a Python function and turn it into a function object which I can then call. For example,
myString = "def add5(x):
return x + 5"
myFunc = myString.toFunction() <-- something like this?
print myFunc(10) <-- should print 15
My desire to be able to do this arose from a problem posed in my theoretical foundations of computing class, which operates under an assumption of SISO (String in, String out). In particular, we are examining the uncomputable problem yesOnString(P,I), which returns "yes" if P(I) = "yes" and "no" otherwise. Thus I want to be able to have a function P passed in String form as a parameter, and then have the function convert the string into a function which it then calls.
eval()wouldn't work butexec()would but it would just introduceadd5as the function name. @SufiyanGhori you can't useliteral_evalthat is only for literals - and this is code.exec()is what the OP wants. Even if it supportsexec('import os'),exec('os.system("rm -rf blah")').