I have a huge python code with lots of print statements useful for debugging. I want to be able to enable or disable them in one go, without poring over the hundreds of printf
's and commenting them each time.
In C, a #define
can be used to comment out unneeded parts of the code using #ifdef
like this-
#define debug
#ifdef debug
printf("Debug on")
#endif
If I don't want to be in debug mode, I can simply comment #define debug and none of my print
statements will compile.
How can this functionality be done in Python?
Python has no direct equivalent of C's macros because it has no preprocessor and does not distinguish between compile-time and run-time like C does.
A simple solution however is to put your
print
lines inside an if-statement:You can then just change the
False
toTrue
to have them be executed.Similarly, you could do:
and then change the
DEBUG
name toTrue
.A third (and probably the best) option would be to use Python's built-in
__debug__
flag:__debug__
is a constant likeNone
and is set toTrue
if Python is launched without a-O
option (it is in debug mode). Otherwise, if a-O
option is set (we are in optimized/production mode),__debug__
will be set toFalse
and the code using it will be entirely ignored by the interpreter so that there is no performance penalty.