在python中使用types.FunctionType方法動態生成函數,具體方法如下:
from types import FunctionType, CodeType
code_1 = """
def uuid()->str:
import uuid
return str(uuid.uuid1())"""
foo_compile = compile(code_1 , "
", "exec") foo_code = [ i for i in foo_compile.co_consts if isinstance(i, CodeType)][0]
globals()['uuid'] = FunctionType(foo_code, globals())
func = globals()['uuid']
print(func())