This question already has answers here:
Python: dynamically create function at runtime
(5个答案)
3个月前关闭。
我有字符串格式的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

这是一个简单的字符串函数,用于添加列表元素。我正在寻找一个实用程序模块,它可以返回函数的对象add
function_obj = some_function(s)
print 'type:', type(function_obj)
type: <type 'function'>

最佳答案

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

code_obj = compile(s, '<string>', 'exec')

然后使用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

07-24 09:52
查看更多