Skip to content Skip to sidebar Skip to footer

Possible To Turn An Input String Into A Callable Function Object In Python?

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 +

Solution 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.


Post a Comment for "Possible To Turn An Input String Into A Callable Function Object In Python?"