Using debug print routine inside assert

Ben Finney bignose-hates-spam at
Tue Nov 4 13:56:10 CET 2003

On Tue, 04 Nov 2003 14:15:30 +0200, Edvard Majakari wrote:
> Today I shortly discussed the problems in using print statements for
> debugging problems in Python. Often in coding, in addition to asserts it
> is nice to have a debug routine like
> import time
> global DEBUG_LVL = 0
> ...
> def debug(msg, threshold=1):
>     if threshold > DEBUG_LVL:
>        return
>     print "%s %s\n" %(time.strftime("%d%m%y %H:%M:%S"), msg)
> # somewhere in the program
> debug("subfrobnicate(%s, %s) returned %s" %(p1, p2, subfrobnicate(p1, p2)))

The debug routine looks elegant and useful; thanks.

The instance of its use is the problem.

You're performing two discrete operations: get the result of the
subfrobnicate() call, and then emit a debug message.  The problem isn't
with the debug message -- it's with the subfrobnicate() call.  Or more
precisely, the fact that you only seem to be using it for the debug()

If the code only ever uses subfrobnicate() when you emit the debug
message -- which isn't going to occur in the released program -- you
don't really need to see it.

    # somewhere in the program
    debug( "p1 is %s, p2 is %s", % ( p1, p2 ) )

If the result of subfrobnicate() is important enough that you want to
track it with a debug() call, it's probably because you're using the
same result elsewhere.  So why are you calling it each time it's needed?
Calculate it, emit the message, then use it some more.

    # somewhere in the program
    sf_result = subfrobnicate( p1, p2 )
    debug( "sf_result is %s (subfrobnicated from %s, %s)" %
        ( sf_result, p1, p2 )
    do_other_stuff( sf_result )

Either the subfrobnicate() call is a waste of cycles -- remove it.  Or,
it's a necessary part of the program -- keep its result for use in the
debug message *and* the main program.

 \       "If you make people think they're thinking, they'll love you; |
  `\         but if you really make them think, they'll hate you."  -- |
_o__)                                                        Anonymous |
Ben Finney <>

More information about the Python-list mailing list