python动态创建函数

代码示例

from types import FunctionType, CodeType

code_1 = """
def uuid()->str:
    import uuid
    return str(uuid.uuid1())"""

# 编译为字节代码对象
foo_compile = compile(code_1, "<string>", "exec")
# print(foo_compile)

# 遍历字节代码对象,获取到code类型的对象
foo_code = [i for i in foo_compile.co_consts if isinstance(i, CodeType)][0]
# print(type(foo_code))

# 1、FunctionType创建新函数(根据compile生成的code对象生成),2、在globals当前命名空间新增key
globals()['uuid'] = FunctionType(foo_code, globals())

# 执行动态添加的代码
func = globals()['uuid']
print(func())

参考文章
https://blog.csdn.net/qq_27371025/article/details/128118862
https://www.jianshu.com/p/a4d59d1d3aa5

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容