如何编写一个可以打印其参数名称和值的函数?

时间:2013-07-11 07:54:04

标签: python debugging

调试具有如下功能非常有用:

a = np.arange(20)
debug_print(a)

上面应该打印

variable: a
val: [...]

非常感谢。

1 个答案:

答案 0 :(得分:1)

请尝试以下代码:

import inspect
import re

def debug_print(*args):
    lines = ''.join(inspect.stack()[1][4])
    matched = re.search('debug_print\((.*?)\)', lines).group(1)
    names = map(str.strip, matched.split(','))
    for name, value in zip(names, args):
        print('{} = {}'.format(name, value))

a = 1
b = 2
debug_print(a, b)
debug_print('a')
debug_print('a,aa') # Not work well for this case.