无法从评估的 lambda 函数中获取源代码
Can't get source code from an evaluated lambda function
我遇到了这个有趣的事实,我想知道如何克服它。通过使用 inspect
很容易获得 lambda 的源代码。但是,一旦您 return 来自 eval
语句的完全相同的 lambda,获取源函数就会失败。
import inspect
f = lambda a: a*2
f2 = eval("lambda a: a*2")
inspect.getsource(f), inspect.getsource(f2)
/usr/lib/python3.7/inspect.py in getsource(object)
971 or code object. The source code is returned as a single string. An
972 OSError is raised if the source code cannot be retrieved."""
--> 973 lines, lnum = getsourcelines(object)
974 return ''.join(lines)
975
/usr/lib/python3.7/inspect.py in getsourcelines(object)
953 raised if the source code cannot be retrieved."""
954 object = unwrap(object)
--> 955 lines, lnum = findsource(object)
956
957 if istraceback(object):
/usr/lib/python3.7/inspect.py in findsource(object)
784 lines = linecache.getlines(file)
785 if not lines:
--> 786 raise OSError('could not get source code')
787
788 if ismodule(object):
OSError: could not get source code
有没有办法解决这个问题并获取评估代码的源代码?
Functions don't remember their source code - all they know is the
filename and line numbers they came from. If the function definition
wasn't in a physical file that is still available, then it is utterly
impossible for inspect.getsource() to work. You'd need a decompiler,
instead.
谢谢,杰森哈珀
我遇到了这个有趣的事实,我想知道如何克服它。通过使用 inspect
很容易获得 lambda 的源代码。但是,一旦您 return 来自 eval
语句的完全相同的 lambda,获取源函数就会失败。
import inspect
f = lambda a: a*2
f2 = eval("lambda a: a*2")
inspect.getsource(f), inspect.getsource(f2)
/usr/lib/python3.7/inspect.py in getsource(object)
971 or code object. The source code is returned as a single string. An
972 OSError is raised if the source code cannot be retrieved."""
--> 973 lines, lnum = getsourcelines(object)
974 return ''.join(lines)
975
/usr/lib/python3.7/inspect.py in getsourcelines(object)
953 raised if the source code cannot be retrieved."""
954 object = unwrap(object)
--> 955 lines, lnum = findsource(object)
956
957 if istraceback(object):
/usr/lib/python3.7/inspect.py in findsource(object)
784 lines = linecache.getlines(file)
785 if not lines:
--> 786 raise OSError('could not get source code')
787
788 if ismodule(object):
OSError: could not get source code
有没有办法解决这个问题并获取评估代码的源代码?
Functions don't remember their source code - all they know is the filename and line numbers they came from. If the function definition wasn't in a physical file that is still available, then it is utterly impossible for inspect.getsource() to work. You'd need a decompiler, instead.
谢谢,杰森哈珀