【问题标题】:How can we print the variable name along with its value in python, which will be useful during debugging?我们如何在 python 中打印变量名及其值,这在调试过程中会很有用?
【发布时间】:2015-06-30 08:47:44
【问题描述】:

我已经多次写过类似的东西:

print 'customer id: ', customerId

我想要一个函数,它可以打印变量名和值

>>myprint(customerId)

>>customerId: 12345

【问题讨论】:

  • @Kasra 他有很多变量他不想做同样的打字而是想调用一个函数
  • 如果12345 被多个名称引用怎么办?还是没有(例如,仅通过列表引用)?阅读:nedbatchelder.com/text/names.html
  • test_str = 'hello'; myprint(test_str); 会发生什么?变量test_strTrueValue"hello" 将传递给函数myprint,而不是与VariableName 一起传递。
  • @jonrsharpe 这就是我在说什么

标签: python inspection


【解决方案1】:

完全按照您的要求进行操作涉及在符号表中进行 O(n) 查找,恕我直言,这很糟糕。

如果可以传递变量名对应的字符串,可以这样做:

import sys

def myprint(name, mod=sys.modules[__name__]):
    print('{}: {}'.format(name, getattr(mod, name)))

测试:

a=535
b='foo'
c=3.3

myprint('a')
myprint('b')
myprint('c')

将打印:

a: 535
b: foo
c: 3.3

您也可以通过传递第二个参数来使用它来打印来自另一个模块的变量,例如:

>>> import os
>>> myprint('pathsep', os)
pathsep: :

【讨论】:

  • 回答了 OP 的问题。
  • 查找表不是哈希表吗?在这种情况下,这应该在 O(1) 时间内起作用。
  • 代码是for k, v in globals().items(): if v is a: return k,也就是O(n)
【解决方案2】:

基本上,每次调用它时,您都需要将变量名称手动输入到辅助函数的参数中,这与直接将字符串格式化为打印消息相同。

另一种可能的(没用的?)见鬼的可能是:

import re
regex = re.compile("__(.+)")
def check_value(checkpoint_name):
    print "============"
    print checkpoint_name
    print "============"
    for variable_name, variable_value in globals().items():
        if regex.match(variable_name) is None:
            print "%s\t:\t%s" % (variable_name, str(variable_value))
    print "============"

,每次调用都会在全局范围内打印所有非系统保护的声明变量。要调用该函数,请执行

 a = 0
 check_value("checkpoint after definition of a")

 b = 1
 check_value("checkpoint after definition of b")

随意根据您的需要自定义功能。我只是想出了这个,不确定这是否按你想要的方式工作......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 2017-04-11
    • 2010-10-10
    • 1970-01-01
    相关资源
    最近更新 更多