I have a content of a function given by a string. I'm looking for a way how to convert this string into a function object to call it.
content = "def my_function(x):\n return x**2"
my_function = extract_function_from_string(content) # extract_function_from_string ???
print my_function(5) # prints 25
Perhaps, there's a way to convert the string into a python module and extract the function from it
You can use exec
>>>content = "def my_function(x):\n return x**2"
>>>exec content
>>>my_function(5)
25
For Python 3.x
>>>exec(content)
Try the exec
statement:
>>> content = "def my_function(x):\n return x**2"
>>> exec content
>>> my_function(5)
25
If you know the function name, you can run exec on the string. Eval will not work as it only targets expressions. See \\r\\n vs \\n in python eval function . If you don't know the function name, but all your function have the same format you can try something like this:
def extract_function_from_string(content):
exec(content)
start = 4
end = content.find("(")
function_name = content[start:end]
return eval(function_name)
my_function = extract_function_from_string("def my_function(x):\n return x**2")
print my_function(5)
The train has left the safe and sound python station a long time ago, but I guess this is just a curiosity.
Here is something that does not leave safe train of python completely.
def extract_function_from_string(content, function_index=0):
import ast
tree = ast.parse(content, mode='exec')
function = tree.body[function_index]
module = ast.Module([function])
exec(compile(module, filename="<ast>", mode='exec'))
return locals()[function.name]
content = "def my_function(x):\n return x**2"
my_function = extract_function_from_string(content) # extract_function_from_string ???
print(my_function(5)) # prints 25
You can use the eval function to do this. eg eval("print('Hello')").
However, do be advised that this can be a security risk, and there is probably a better way of doing it than parsing a string.
a = "lambda x:x**2"
my_func = eval(a)
print my_func(3)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.