Spundun
Spundun

Reputation: 4034

Python equivalent for #ifdef DEBUG

In C we write code like

#ifdef DEBUG
printf("Some debug log... This could probably be achieved by python logging.Logger");
/* Do some sanity check code */
assert someCondition
/* More complex sanitycheck */
while(list->next){
assert fooCheck(list)
}

#endif

Is there a way to do this in python?

Edit: I got my answer, and more :) Paolo, Steven Rumbalski and J Sebastian gave me the information I was looking for. Thanks das for the detailed answer, although I'll probably not use a preprocessor right now.

J Sebastian, whose comment got deleted because the answer in which he posted his comment, deleted his answer I think. He said I could use the isEnabledFor() method in Logger to feed a conditional.

Thanks everyone for your inputs. This is my first question. I wish I could accept paolo, or j sebastian's answers. But since those were offered as comments, I'll accept das' answer.

I will probably use either http://nestedinfiniteloops.wordpress.com/2012/01/15/if-debug-python-flavoured/ or Logger.isEnabledFor()

Upvotes: 63

Views: 56341

Answers (6)

DenisSh
DenisSh

Reputation: 41

I use another approach - to test module as standalone/direct running:

import ...

DEBUG = False

....

def main():
    pass

if __name__ == '__main__':
    DEBUG = True
    main()

It gives - flexibility to run as module inside project DEBUG will False, when standalone DEBUG will True. This suitable for example to load data from local file or from request:

def load_csv():
    fn = get_csv_filename()  # will return path depending DEBUG
    if DEBUG:
        if not exists(fn):
            store_df(request_bond_list(), fn)
        return pd.read_csv(fn)
    return request_bond_list()

It also help me to control a path depending DEBUG mode. As you know when module placed in different directory from a main code the path will be 'module' directory in case we run module as standalone (for tests), but when we implements methods from this module inside 'main' then path will set to root of your project. So you can use DEBUG to tune the path for different situations

(or you can directly change 'path' in "if __name__ == '__main__':")

Upvotes: 0

majid lesani
majid lesani

Reputation: 197

check the result of sys.gettrace() is None. That will mean that there is no debugger

import sys
if sys.gettrace():
    print("debug mode!")
else:
   print("debug mode is off!")

Upvotes: 2

das_weezul
das_weezul

Reputation: 6142

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.

Upvotes: 11

doctaphred
doctaphred

Reputation: 2654

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!

Upvotes: 40

Mohammad Shahid Siddiqui
Mohammad Shahid Siddiqui

Reputation: 4190

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.

Upvotes: 123

Julien Vivenot
Julien Vivenot

Reputation: 2250

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

Upvotes: 2

Related Questions