2

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.

18
  • 1
    @Kingsley eval() wouldn't work but exec() would but it would just introduce add5 as the function name. @SufiyanGhori you can't use literal_eval that is only for literals - and this is code. Commented Jan 31, 2019 at 4:11
  • @AChampion - I think exec() is what the OP wants. Even if it supports exec('import os'), exec('os.system("rm -rf blah")'). Commented Jan 31, 2019 at 4:16
  • Yes, the obligatory warnings. Commented Jan 31, 2019 at 4:18
  • @TigerhawkT3: This is not a duplicate. OP has clearly said he want to convert string to function and store it as a varialbe. This is not answered in the origianl question and answer. Commented Jan 31, 2019 at 4:59
  • followup question: stackoverflow.com/questions/54453678/… Commented Jan 31, 2019 at 5:15

1 Answer 1

-1

This is possible with the Python built-in exec() function.

myString = "def myFunc(x): return x + 5"
exec( myString )  # myFunc = myString.toFunction() <-- something like this?
print( myFunc(10) )  #   <-- should print 15

If you want to keep the same naming pattern

myString = "def add5(x): return x + 5"
exec( myString )  # myFunc = myString.toFunction() <-- something like this?
myFunc = add5
print( myFunc(10) )  #   <-- should print 15

In terms of safety: exec() executes the given string, any given string.

import os.system
os.system("format C:")  # etc.

So be really careful how it's used. Certainly not on any sort of user's input.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.