调试复杂代码时,有时需要转换:
def myfunction(self):
...
self.foo.bar = self.baz.bla
进入
def myfunction(self):
...
self.foo.bar = self.baz.bla
print("myfunction", "self.foo.bar", self.foo.bar) # add this for debugging purposes
是否有一种方法(使用装饰器或上下文管理器或其他工具)来自动print
变量名和下一行代码分配的值(可能还有当前函数)?
示例:
def myfunction(self):
...
with debug:
self.foo.bar = self.baz.bla
将输出:
"myfunction self.foo.bar 123"
您可以使用检查模块:
from inspect import currentframe
def f():
a = 5
debug_print("a")
def debug_print(var):
locals = currentframe().f_back.f_locals
print(f"{var} = {locals[var]}")
f()
另请参见:Access parent namespace in python
我承认,这只是您所要求的一部分,但也许是一个好的开始。
编辑:好的,这是怎么回事:
from inspect import currentframe, getsourcelines
def f():
a = 5
debug_print()
def debug_print():
frame = currentframe().f_back
locals = frame.f_locals
source, start = getsourcelines(currentframe().f_back.f_code)
var = source[frame.f_lineno - 1 - start].split("=")[0].strip()
print(f"{var} = {locals[var]}")
f()
虽然我没有对它在多大程度上进行测试,但是至少应该进一步指出。