debug print shortcut?

J

John Mudd

When debugging python, I add print statements such as these.

print 'i=%s' % `i`
print 'foo()=%s' % `foo()`
print 'a,b,c=%s' % `a,b,c`

I just want to dump the value of a variable or expression. But I
don't like having to type the expression twice, everytime. I can
solve this in 'C' with a preprocessor macro. Can it be solved in
python?

John
 
D

Donald 'Paddy' McCarthy

John said:
When debugging python, I add print statements such as these.

print 'i=%s' % `i`
print 'foo()=%s' % `foo()`
print 'a,b,c=%s' % `a,b,c`

I just want to dump the value of a variable or expression. But I
don't like having to type the expression twice, everytime. I can
solve this in 'C' with a preprocessor macro. Can it be solved in
python?

John
I found this:
.... print "%s = %s\n" % (s, eval(s,glob,loc) )
....a = 55


Cheers, Pad.
 
R

Roel Schroeven

John said:
When debugging python, I add print statements such as these.

print 'i=%s' % `i`
print 'foo()=%s' % `foo()`
print 'a,b,c=%s' % `a,b,c`

I just want to dump the value of a variable or expression. But I
don't like having to type the expression twice, everytime. I can
solve this in 'C' with a preprocessor macro. Can it be solved in
python?

def printdebug(s):
print '%s = %s' % (s, `eval(s)`)
 
J

Jeff Epler

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)
.... y = 3
.... debug("y+1")
....'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 likedebug(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-----
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,201
Messages
2,571,049
Members
47,652
Latest member
Campbellamy

Latest Threads

Top