When debugging, I like to print out all the inputs and outputs of a function (I know I need a better IDE, but humour me, this could be used for error reporting). So, I’d ideally like to have:
@debuggable
def myfunc(argA,argB,argC):
return argB+1
and use a global variable to switch on or off debugging. No, you don’t like globals either, I guessed.
The best I can come up with is:
DEBUG = True
def debuggable(func):
if DEBUG:
def decorated(*args):
print "Entering ",func.func_name
print " args ",args
ret = func(*args)
print ret
return ret
return decorated
else:
return func
@debuggable
def myfunc(this,that):
return this+that
And running:
>>> myfunc(1,3)
Entering myfunc
args (1, 3)
4
How can I improve that?
Use a debugger. Seriously. Decorating every function you want to keep track is a bad idea.
Python has a debugger included, so you don’t need a good IDE.
If you don’t want to use a debugger, you can use the trace function.
That prints:
Even easier would be to use Winpdb:
It is a platform independent graphical GPL Python debugger with support for remote debugging over a network, multiple threads, namespace modification, embedded debugging, encrypted communication and is up to 20 times faster than pdb.
Features:
(source: winpdb.org)