if(debug), optimized away?

Alex Martelli aleax at aleax.it
Fri Jul 26 03:18:34 EDT 2002


M wrote:

> I would like to use something like this when running in
> debug mode:
> 
> if(debug):
>    if(items > 9):
>      print "fatal error..."
>    do_some_check_foo(42)
>    ...
> 
> 
> If I set debug=0, is this code optimized away as in most
> C/C++?? compilers?

No, but if you used:

if __debug__:
    if items > 9:
        andso(on)

then running with python -O would indeed remove the code.


> The reason for asking is that I would like to have A LOT of
> debugging code and would like to avoid the performance penalty
> when not runing in debug mode.

That's exactly what __debug__ and the -O flag are for.  The
bytecode files produced are bleep.pyo instead of bleep.pyc,
and they remove line numbers, asserts, and stuff done within
"if __debug__:" guards.

You can't effectively assign __debug__ at runtime of course --
by that time the bytecode has already been compiled.  You need
to indicate that you're running-optimized with "python -O" as
the command to run your script.

Note that the semantics don't change -- you only save code
space by effectively removing the "if __debug__:" guarded
blocks.  That may indirectly translate in a little speedup
if it helps your cache / VM be used more effectively.


Alex




More information about the Python-list mailing list