我的任务有点不寻常且出乎意料地令人费解 - 显示特定类的方法实现的源代码。
In [1]: class Demonstration:
...: def cost():
...: return 42
...:
In [2]: class OtherDemo:
...: def cost():
...: return 43
...:
在此示例中,我想在任一给定类的适当缩进处找到文本 def cost(): 和以下行。
inspect 或 dis 之类的模块几乎就是我要找的东西,但我想显示 python 代码,例如在回溯期间显示的代码;不是字节码。
我也不反对解析源文件 - 是否有文本编辑器可用于自动完成或缩进计算的库,可以在类中找到特定方法?
请您参考如下方法:
听起来 inspect 库正是您所需要的,特别是函数 getsourcelines :
In [1]: def foo(x):
...: x += 3
...: x += 4
...: return x
...:
In [2]: import inspect
In [3]: inspect.getsourcelines(foo)
Out[3]: (['def foo(x):\n', ' x += 3\n', ' x += 4\n', ' return x\n'], 1)
In [4]: source_code = _
In [6]: print(''.join(source_code[0]))
def foo(x):
x += 3
x += 4
return x
来自文档:
Return a list of source lines and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of the lines corresponding to the object and the line number indicates where in the original source file the first line of code was found. An IOError is raised if the source code cannot be retrieved.
