Spundun Spundun - 3 months ago 24
Python Question

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()

Answer

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.