如何从字符串中获取python函数对象

vas*_*aur 4 python python-2.7

我有字符串格式的 python 函数,我想在程序范围内获取这些函数的 python 对象。我已经尝试过exec()eval()ast.literal_eval()这些都没有返回函数对象。

例如:

s = "def add(args):\n    try:\n        return sum([int(x) for x in args])\n    except Exception as e:\n        return 'error'\n
Run Code Online (Sandbox Code Playgroud)

这是字符串中的一个简单函数,用于添加列表元素。我正在寻找一个可以返回函数对象的实用模块add

function_obj = some_function(s)
print 'type:', type(function_obj)
type: <type 'function'>
Run Code Online (Sandbox Code Playgroud)

Abd*_*P M 6

首先将函数(作为字符串)编译为代码对象,即

code_obj = compile(s, '<string>', 'exec')
Run Code Online (Sandbox Code Playgroud)

然后用于types.FunctionType从代码对象创建新的函数类型。

>>> import types
>>> new_func_type = types.FunctionType(code_obj.co_consts[0], globals())
>>> print(type(new_func_type))
<class 'function'>
>>> new_func_type([*range(10)])
45
Run Code Online (Sandbox Code Playgroud)