Python: Print a variable's name and value?

前端 未结 9 1656
一生所求
一生所求 2020-12-13 08:21

When debugging, we often see print statements like these:

print x        # easy to type, but no context
print \'x=\',x   # more context, harder to type
12
x=         


        
9条回答
  •  悲&欢浪女
    2020-12-13 08:56

    You can just use eval:

    def debug(variable):
        print variable, '=', repr(eval(variable))
    

    Or more generally (which actually works in the context of the calling function and doesn't break on debug('variable'), but only on CPython):

    from __future__ import print_function
    
    import sys
    
    def debug(expression):
        frame = sys._getframe(1)
    
        print(expression, '=', repr(eval(expression, frame.f_globals, frame.f_locals)))
    

    And you can do:

    >>> x = 1
    >>> debug('x + 1')
    x + 1 = 2
    

提交回复
热议问题