Search code examples
pythonpreprocessorequivalentdirective

How would you do the equivalent of preprocessor directives in Python?


Is there a way to do the following preprocessor directives in Python?

#if DEBUG

< do some code >

#else

< do some other code >

#endif

Solution

  • There's __debug__, which is a special value that the compiler does preprocess.

    if __debug__:
      print "If this prints, you're not running python -O."
    else:
      print "If this prints, you are running python -O!"
    

    __debug__ will be replaced with a constant 0 or 1 by the compiler, and the optimizer will remove any if 0: lines before your source is interpreted.