idiom for debug code?

Robert Brewer fumanchu at amor.org
Thu Sep 30 13:44:06 EDT 2004


Dan Perl wrote:
> Is there a mechanism or an idiom for adding code for 
> debugging so that it 
> can easily be removed in the production code?  I am thinking 
> of something 
> similar to the C/C++ preprocessor statements with which you 
> can compile an 
> application with the debug code or without it (the default).

>From the docs (http://docs.python.org/ref/assert.html):

----

The simple form, "assert expression", is equivalent to

if __debug__:
   if not expression: raise AssertionError

The extended form, "assert expression1, expression2", is equivalent to

if __debug__:
   if not expression1: raise AssertionError, expression2

These equivalences assume that __debug__ and AssertionError refer to the
built-in variables with those names. In the current implementation, the
built-in variable __debug__ is 1 under normal circumstances, 0 when
optimization is requested (command line option -O). The current code
generator emits no code for an assert statement when optimization is
requested at compile time. Note that it is unnecessary to include the
source code for the expression that failed in the error message; it will
be displayed as part of the stack trace.

Assignments to __debug__ are illegal. The value for the built-in
variable is determined when the interpreter starts.

----

...which implies other uses for __debug__, I think, which might fit your
needs.


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list