debug print shortcut?
Jeff Epler
jepler at unpythonic.net
Sun Jun 6 17:55:59 EDT 2004
Here's one way. You specify the expression as a string, and the value
or the exception raised is printed.
import sys
def debug(expression, depth=1):
frame = sys._getframe(depth)
locals = frame.f_locals
globals = frame.f_globals
try:
value = eval(expression, globals, locals)
except:
value = sys.exc_info()[1]
print >>sys.stderr, "%r -> %r" % (expression, value)
>>> debug("3+3")
'3+3' -> 6
>>> debug("1/0")
'1/0' -> <exceptions.ZeroDivisionError instance at 0x00B6E248>
>>> def f():
... y = 3
... debug("y+1")
...
>>> f()
'y+1' -> 4
Another way would be to pass the result of the expression to debug(),
and use inspect.getsource() to locate the line of code in the caller. I
haven't written this, but usage might look like
>>> debug(3+3)
debug(3+3) -> 6
With this approach, exceptions would be propagated, not handled in
debug().
Jeff
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20040606/627874e1/attachment.sig>
More information about the Python-list
mailing list