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()
Python's "object-based" subset is roughly equivalent to JavaScript. Like JavaScript (and unlike Java), Python supports a programming style that uses simple functions and variables without engaging in class definitions. However, for JavaScript, that's all there is.
To use the and operator in Python, use the keyword and instead of && because there is no && operator in Python. If you use && operator in Python, you will get the SyntaxError. Likewise, || and ! are not valid Python operators. So instead, use or and not operator.
In, Python += adds another value with the variable's value and assigns the new value to the variable.
The Python += operator adds two values together and assigns the final value to a variable. This operator is called the addition assignment operator.
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
python -O abc.py
python abc.py
Observe the difference.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With