Python equivalent for #ifdef DEBUG

Solution 1:

Use __debug__ in your code:

if __debug__:
    print 'Debug ON'
else:
    print 'Debug OFF'

Create a script abc.py with the above code and then

  1. Run with python -O abc.py
  2. Run with python abc.py

Observe the difference.

Solution 2:

Mohammad's answer is the right approach: use if __debug__.

In fact, Python completely removes the if statement if the expression is a static constant (such as True, False, None, __debug__, 0, and 0.0), making if __debug__ a compile-time directive rather than a runtime check:

>>> def test():
...     if __debug__:
...         return 'debug'
...     return 'not debug'
...
>>> import dis
>>> dis.dis(test)
  3           0 LOAD_CONST               1 ('debug')
              2 RETURN_VALUE

The -O option is explained in detail in the python documentation for command line options, and there is similar optimization for assert statements.

So don't use an external preprocessor—for this purpose, you have one built in!

Solution 3:

What you are looking for is a preprocessor for python. Generally you have three options:

  1. Write a selfmade script/program which replaces parts of your sourcecode based on certain templates before passing the result on to the interpreter (May be difficult)
  2. Use a special purpose python preprocessor like pppp - Poor's Python Pre-Processor
  3. Use a general purpose preprocessor like GPP

I recommend trying pppp first ;)

The main advantage of a preprocessor compared to setting a DEBUG flag and running code if (DEBUG == True) is that conditional checks also cost CPU cycles, so it is better to remove code that does not need to be run (if the python interpreter doesn't do that anyway), instead of skipping it.

Solution 4:

If you are looking for assertions in Python, assert is an actual valid python statement. http://docs.python.org/2/reference/simple_stmts.html#assert