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
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)
iD8DBQFAw5LvJd01MZaTXX0RAuVCAJ9efkj4FJ//mb9oErKGhipcje2s6QCfbuw7
2HdglpNUphcWVm+ELtdT2Hk=
=FCVc
-----END PGP SIGNATURE-----