gpt4 book ai didi

python - 如何将函数转换为 str for Python?

转载 作者:太空狗 更新时间:2023-10-29 21:30:36 25 4
gpt4 key购买 nike

假设我有以下 lambda 函数。

fn = lambda x: print(x) 

如果我想把它转换成字符串

"lambda x: print(x)" 

我能做什么?我期待 str(fn)str(fn.__code__) 会这样做,但不是真的......它只是打印出类型、内存位置等。

我也尝试过 pickle.dumps 和 json,但我无法得到我想要的。

如何将函数转换为显示函数定义的字符串?

--- 我想将函数作为输入并将其转换为字符串

最佳答案

如果你已经安装了 dill 就很容易了。 (pip install dill)

from dill.source import getsource
squared = lambda x:x**2
print(getsource(squared))

关于python - 如何将函数转换为 str for Python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44206813/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com