【问题标题】:Removing the redundancy in Python's 'print' with introspection通过内省消除 Python 的“打印”中的冗余
【发布时间】:2014-10-27 00:03:19
【问题描述】:

我经常在调试时发现自己在做这样的事情:

print a.foo, b.bar, c.baz

它打印类似的东西

1 3 4

这是正确的,但没有它应该的那么有用。
我理想地想要被打印出来是这样的:

a.foo: 1, b.bar: 3, c.baz: 4

这很容易通过

print 'a.foo:', a.foo, 'b.bar:', b.bar, 'c.baz:', c.baz

但现在我要写两次相同的东西!

我可以使用某种 Python 技巧(例如自省)来避免重复自己吗?
我在想象这样一个神奇的printexp

printexp('a.foo', 'b.bar', 'c.baz')

但我不熟悉 Python 的自省功能,所以我不确定如何去做。

【问题讨论】:

    标签: python introspection


    【解决方案1】:

    我自己想通了:

    >>> def printexp(*exps, **kwargs):
        import sys
        import inspect
        import itertools
        locs = dict(inspect.currentframe().f_back.f_locals)
        locs.setdefault('_file', kwargs['file'] if 'file' in kwargs else sys.stdout)
        exec('print' + ' ' + '>>' + '_file' + ', ' + (', ' + '_file' + '.write(",")' + ' or ').join(map(lambda exp: '"' + exp.replace('"', '\\"') + ':' + '"' + ', ' + exp, exps)) + '', None, locs)
    
    >>> x = 5
    >>> printexp('x', 'x')
    x: 5, x: 5
    

    【讨论】:

      【解决方案2】:

      这并不完全符合您的要求,但如果您想使用“普通”对象(我指的是用户定义类的对象)来执行此操作,您可能只想这样做:

      print a.__dict__
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-01-07
        • 2011-03-13
        • 2020-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多