===============================================================
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?
==========================================================================================================================
What you are looking for is a
preprocessor for python. Generally you have three options:
- 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)
- Use a special purpose python preprocessor like pppp - Poor's Python Pre-Processor
- Use a general purpose preprocessor like GPP
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.
===========================================================================================================================
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.
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!
==========================================================================================================================
Matt: python has a built in debug mode which I assume is set by that option since the option toggles all the debug mode stuff and it cannot be changed in game.
I could be wrong about that tho - it could be always on.
If it's not always on then you can use if __debug__ instead of regular if statement for debug stuff. Only disadvantage would be that u can't change the setting in game.