gpt4 book ai didi

python - 如何在 python 中准确获取 lambda 函数的代码?

转载 作者:行者123 更新时间:2023-12-04 10:50:32 24 4
gpt4 key购买 nike

我想知道是否有办法获取以下 lambda 函数的代码:

a = {"test": lambda x: x + 123, "test2": lambda x: x + 89}

有没有办法喜欢
print(getsource(a["test"])

那返回:
lambda x: x + 123

我已经知道 inspect 和 dill getsource 函数,但是下面的代码:
import inspect
import dill

if __name__ == "__main__":

a = {"test": lambda x: x + 123, "test2": lambda x: x + 89}

print(inspect.getsource(a["test"]))
print(dill.source.getsource(a["test"]))

返回:
a = {"test": lambda x: x + 123, "test2": lambda x: x + 89}

a = {"test": lambda x: x + 123, "test2": lambda x: x + 89}

最佳答案

我遇到了同样的问题,所以我写了一些我认为至少可以部分解决这个问题的代码。

def get_lambda_source(lambda_func, position):
import inspect
import ast
import astunparse
code_string = inspect.getsource(lambda_func).lstrip()
class LambdaGetter(ast.NodeTransformer):
def __init__(self):
super().__init__()
self.lambda_sources = []

def visit_Lambda(self, node):
self.lambda_sources.append(astunparse.unparse(node).strip()[1:-1])

def get(self, code_string):
tree = ast.parse(code_string)
self.visit(tree)
return self.lambda_sources
return LambdaGetter().get(code_string)[position]
在你的情况下,
print(get_lambda_source(a['test'], 0]))
返回
lambda x: x + 123
请注意,这在 shell 中不起作用。

关于python - 如何在 python 中准确获取 lambda 函数的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59498679/

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