假设我想要一个函数exec_myfunc
,它可以执行输入值为10的任何用户定义函数.用户应该用string定义函数,如下所示:
func1_str = """
def myfunc1(x):
return x
"""
func2_str = """
def myfunc2(x):
return x**2
"""
现在,我使用了一种非常老套的方法,使用正则表达式提取def
到(
之间的函数名,如下所示:
def exec_myfunc(func_str: str):
import re
exec(func_str)
myfunc_str = re.search(r'def(.*)\(', func_str).group(1).strip()
return eval(myfunc_str)(10)
print(exec_myfunc(func1_str))
# 10
print(exec_myfunc(func2_str))
# 100
我想知道这样做的一般和正确的方法是什么?