macro preprocessor, for debugging information

Tim Peters tim_one at email.msn.com
Mon May 3 00:30:21 EDT 1999


[Phil Hunt]
> Imagine I'm writing some code with debugging information:
>
>    debug = 1 \turn debugging on/off
>    def myFunction(a)
>       if debug: print 'running myFunction() a =', a
>       #...rest of myFunction...
>
> When I have finished debugging, I can set debug to 0 and it no longer
> prints the debugging info. All well and good. But I'm still left with
> the run-time overhead of executing the ``if debug'' statement exery
> time I call myFunction().

Things being what they are, the overhead of the "if debug" test is small
compared to the overhead of calling myFunction.  So run some timings with &
without "if debug" blocks and see whether it makes a difference worth
worrying about (rarely does for me ... but sometimes!).

> Is there any way to avoid the overhead,  e.g. like C's:
>
> #if DEBUG
>    printf("a = %d\n", a);
> #endif

There is *a* simple way, but it's a Big Hammer:  unique among all the names
in the universe, the builtin name __debug__ is evaluated at compile-time.
By default its value is 1; when Python is run with -O its value is 0.  The
other half of the puzzle is that Python doesn't generate any code for an
if-block of the form

    if 0:  # or 0L or 0.0
        xxx
or
    if "":
        xxx

Putting those together,

    if __debug__:
        print 'running myFunction() a =', a

generates code only if you don't run with -O (in which case it does generate
code to load and test __debug__, in case you want to dynamically set it to 0
at runtime; with -O the whole block vanishes).

That's it.  A different straightforward approach that leaves Python out of
it is to use a text editor <wink>; e.g., flipping between

    if 1: # DEBUG_IO_FROBNICATION
and
    if 0: # DEBUG_IO_FROBNICATION

That is, easy patterns for the search-and-replace tool of your choice to
find.

perl-makes-a-pretty-good-python-preprocessor<0.9-wink>-ly y'rs  - tim






More information about the Python-list mailing list