【问题标题】:How to write a function that can print the name and value of its argument? [duplicate]如何编写一个可以打印其参数的名称和值的函数? [复制]
【发布时间】:2013-07-11 07:54:04
【问题描述】:

这样的功能对调试非常有用:

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

上面应该打印

variable: a
val: [...]

非常感谢。

【问题讨论】:

  • 您正试图在调用框架中打印变量的名称。函数本身将具有该参数的不同名称。您正在尝试做的是相当...麻烦。打印价值还不够吗?
  • 我有一个包含六个中间步骤的函数。知道正在打印哪个变量真的很有帮助,而不必每次都打印 'var', var。
  • 这与print debug_print(var) 有何不同?那时你已经知道var了。
  • 将其设为关键字参数 (debug_print(var=var)),这很简单,请参阅链接的欺骗。

标签: python debugging


【解决方案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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-14
    • 2012-11-28
    • 2011-01-04
    • 2012-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多