Search code examples
pythondebugging

Print a variable's name and value


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= 12

How can write a function that will take a variable or name of a variable and print its name and value? I'm interested exclusively in debugging output, this won't be incorporated into production code.

debugPrint(x)    #  or
debugPrint('x')
x=12

Solution

  • 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