conditional running of code portion

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Aug 5 02:30:49 EDT 2012


On Sat, 04 Aug 2012 21:16:04 -0700, JW Huang wrote:

> Hi,
> 
> How can I implement something like C++'s conditional compile.
> 
> if VERBOSE_MODE: print debug information else: do nothing
> 
> But I don't want this condition to be checked during runtime as it will
> slow down the code.


You've profiled your code and found that checking a flag is a bottleneck 
in your application? I'd hate to think you were wasting your time trying 
to avoid "slowing down" your code by an insignificant amount that nobody 
will ever notice.

In general, the way to do C-like conditional compiles is to use C, or at 
least to use another language that isn't Python. Almost everything 
happens at runtime in Python. Possibly PyPy can optimise away unnecessary 
checks, but CPython doesn't.

One of the very few exceptions: you can disable code at compile time like 
this:

if __debug__:
    do_something()


compiles to the byte-code equivalent of:

do_something()


under normal circumstances, and to nothing at all if Python is running 
with the -O optimize flag. 


If you are working in a tight loop, you can do this:

if VERBOSE_FLAG:
    for item in loop:
        print(DEBUG_INFORMATION)
        do_actual_work(item)
else:
    for item in loop:
        do_actual_work(item)




-- 
Steven



More information about the Python-list mailing list