访问调用函数的 vars()

Access vars() of calling function

调试时,我经常发现打印变量的名称和内容很有用。

a = 5
b = 7
print("a: "+str(a)+"\n b: "+str(b))

我想写一个函数来实现这个。到目前为止,我有以下功能:

def dprint(varslist, *varnames):
    string = [var+": "+str(varslist[var]) for var in varnames]
    print("\n".join(string))

它的用法示例是

a = 5
b = 7
dprint(vars(), "a", "b")

我的问题是:有没有什么方法可以编写 dprint() 使得 vars() 不需要在每次调用时都显式传递给它?具体来说,有没有办法让 dprint() 访问其调用函数的 vars()?

那么,我们可以改写为

def dprint(*varnames):
    varslist = # magic code that gets vars() from calling function
    string = [var+": "+str(varslist[var]) for var in varnames]
    print("\n".join(string))

在 Python 中,您可以调试调用 breakpoint 内置函数的程序。

使用sys._getframe:

Return a frame object from the call stack. If optional integer depth is given, return the frame object that many calls below the top of the stack. If that is deeper than the call stack, ValueError is raised. The default for depth is zero, returning the frame at the top of the call stack.

然后使用f_locals获取caller的本地变量。

import sys

def dprint(*varnames):
    caller = sys._getframe(1)  # depth=1
    for var in varnames:
        print(f'{var}: {caller.f_locals.get(var)}')

def foo():
    a = 5
    b = 7
    dprint("a", "b")

foo()

输出:

a: 5
b: 7