idiom for debug code?

Kjetil Torgrim Homme kjetilho at
Sat Oct 2 08:02:16 CEST 2004

[Dan Perl]:
>   Is there a mechanism or an idiom for adding code for debugging so that it 
>   can easily be removed in the production code?  I am thinking of something 
>   similar to the C/C++ preprocessor statements with which you can compile an 
>   application with the debug code or without it (the default).

assert is nice, but it's not really what I call debug code -- that's
code which should stay.

for "true" debug code, use the logging module and emit debug messages
with logging.debug("...").  you can raise the debug level if you don't
need them.

or define your own debug() function.  to disable debug, simply bind a
null function to that name.  this rebinding can be done dynamically,
of course.  (this is what the logging module does with unwanted log

in either case, you may want to avoid code like:

   debug("Mother's smell is %s, number of taunts %d" % (fruit, count))

since Python won't be smart enough to skip the string interpolation.
instead, write it as

   debug("Mother's smell is %s, number of taunts %d", fruit, count)

and do the interpolation inside the debug function.
Kjetil T.

More information about the Python-list mailing list