[英]How can I get exactly the code of a lambda function in python?
I would like to know if there is a way to get the code of the following lambda functions:我想知道是否有办法获取以下 lambda 函数的代码:
a = {"test": lambda x: x + 123, "test2": lambda x: x + 89}
Is there a way to like有没有办法喜欢
print(getsource(a["test"])
That returns :那返回:
lambda x: x + 123
I'm already aware of inspect and dill getsource functions but the following code:我已经知道 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"]))
Returns:返回:
a = {"test": lambda x: x + 123, "test2": lambda x: x + 89}
a = {"test": lambda x: x + 123, "test2": lambda x: x + 89}
I ran into the same problem so I wrote a few code that I believe can at least partially address this.我遇到了同样的问题,所以我写了一些我认为至少可以部分解决这个问题的代码。
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]
In your case,在你的情况下,
print(get_lambda_source(a['test'], 0]))
returns返回
lambda x: x + 123
Note this doesn't work in the shell.请注意,这在 shell 中不起作用。
How about the following function mygetsource
?下面的函数mygetsource
怎么mygetsource
?
import inspect
def mygetsource(l, n):
s = inspect.getsource(l[n])
s = s[s.index('{')+1:-2]
d = {x[1:x.index(':')-1]: x[x.index(':')+2:] for x in s.split(', ')}
return d[n]
a = {"test": lambda x: x + 123, "test2": lambda x: x + 89}
print(mygetsource(a, "test"))
print(mygetsource(a, "test2"))
b = {'func1': lambda y: y * 10, 'func2': lambda z: z ** z}
print(mygetsource(b, "func1"))
print(mygetsource(b, 'func2'))
Below is the result:结果如下:
lambda x: x + 123
lambda x: x + 89
lambda y: y * 10
lambda z: z ** z
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.