[英]how to convert function to str for Python?
假設我有以下 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))
嘗試使用inspect
,它是 Python3 標准庫的一部分:
import inspect
func = lambda e: e**2
print(inspect.getsource(func))
返回一個字符串:
func = lambda e: e**2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.