views:

74

answers:

2

I find myself adding debugging "print" statements quite often -- stuff like this:

print("a_variable_name: %s" % a_variable_name)

How do you all do that? Am I being neurotic in trying to find a way to optimize this? I may be working on a function and put in a half-dozen or so of those lines, figure out why it's not working, and then cut them out again.

Have you developed an efficient way of doing that?

I'm coding Python in Emacs.

+1  A: 

Don't do that. Use a decent debugger instead. The easiest way to do that is to use IPython and either to wait for an exception (the debugger will set off automatically), or to provoke one by running an illegal statement (e.g. 1/0) at the part of the code that you wish to inspect.

Olivier
+1 for use the right tool, he is trying to hammer a nail with a swiss army knife
BlueRaja - Danny Pflughoeft
+2  A: 

Sometimes a debugger is great, but sometimes using print statements is quicker, and easier to setup and use repeatedly.

This may only be suitable for debugging with CPython (since not all Pythons implement inspect.currentframe and inspect.getouterframes), but I find this useful for cutting down on typing:

In utils_debug.py:

import inspect    
def pv(name):
    record=inspect.getouterframes(inspect.currentframe())[1]
    frame=record[0]
    val=eval(name,frame.f_globals,frame.f_locals)
    print('{0}: {1}'.format(name, val))

Then in your script.py:

from utils_debug import pv

With this setup, you can replace

print("a_variable_name: %s' % a_variable_name)

with

pv('a_variable_name')

Note that the argument to pv should be the string (variable name, or expression), not the value itself.

To remove these lines using Emacs, you could

C-x (   # start keyboard macro
C-s pv('
C-a
C-k     # change this to M-; if you just want to comment out the pv call
C-x )   # end keyboard macro

Then you can call the macro once with C-x e or a thousand times with C-u 1000 C-x e

Of course, you have to be careful that you do indeed want to remove all lines containing pv(' .

unutbu