When debugging, we often see print statements like these:
JavaScript
x
5
1
print x # easy to type, but no context
2
print 'x=',x # more context, harder to type
3
12
4
x= 12
5
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.
JavaScript
1
4
1
debugPrint(x) # or
2
debugPrint('x')
3
x=12
4
Advertisement
Answer
You can just use eval
:
JavaScript
1
3
1
def debug(variable):
2
print variable, '=', repr(eval(variable))
3
Or more generally (which actually works in the context of the calling function and doesn’t break on debug('variable')
, but only on CPython):
JavaScript
1
9
1
from __future__ import print_function
2
3
import sys
4
5
def debug(expression):
6
frame = sys._getframe(1)
7
8
print(expression, '=', repr(eval(expression, frame.f_globals, frame.f_locals)))
9
And you can do:
JavaScript
1
4
1
>>> x = 1
2
>>> debug('x + 1')
3
x + 1 = 2
4