打印传递给函数的变量的名称 [英] Printing names of variables passed to a function
问题描述
在某些情况下,我想像这样打印调试风格的输出:
In some circumstances, I want to print debug-style output like this:
# module test.py
def f()
a = 5
b = 8
debug(a, b) # line 18
我想要 debug
函数打印以下内容:
I want the debug
function to print the following:
debug info at test.py: 18
function f
a = 5
b = 8
我认为应该可以通过使用检查模块找到堆栈框架,然后找到适当的行,查找该行中的源代码,获取参数的名称那里。可以通过移动一个堆栈帧来获取功能名称。 (参数的值很容易获得:它们直接传递给函数 debug
。)
I am thinking it should be possible by using inspect module to locate the stack frame, then finding the appropriate line, looking up the source code in that line, getting the names of the arguments from there. The function name can be obtained by moving one stack frame up. (The values of the arguments is easy to obtain: they are passed directly to the function debug
.)
我在正确的轨道上?有没有可以参考的食谱?
Am I on the right track? Is there any recipe I can refer to?
推荐答案
您可以按照以下几点做一些事情:
You could do something along the following lines:
import inspect
def debug(**kwargs):
st = inspect.stack()[1]
print '%s:%d %s()' % (st[1], st[2], st[3])
for k, v in kwargs.items():
print '%s = %s' % (k, v)
def f():
a = 5
b = 8
debug(a=a, b=b) # line 12
f()
test.py:12 f()
a = 5
b = 8
这篇关于打印传递给函数的变量的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!