if(debug), optimized away?
Michael Chermside
mcherm at destiny.com
Thu Jul 25 14:23:06 EDT 2002
> I would like to use something like this when running in
> debug mode:
>
> if(debug):
> if(items > 9):
> print "fatal error..."
> do_some_check_foo(42)
> ...
>
>
> If I set debug=0, is this code optimized away as in most
> C/C++?? compilers?
>
> The reason for asking is that I would like to have A LOT of
> debugging code and would like to avoid the performance penalty
> when not runing in debug mode.
>
> Are there other, perhaps more Pythonish, ways of doing the same
> thing?
No, it is not optimized away.
I would recomend the following as being pythonic, but others might not
agree, so get other opinions:
# WARNING: Untested Code
def itemsAreLT9AndValid(items):
if items > 9:
print "fatal error..."
do_some_check_foo(42)
... LATER ON, in your code ...
... code here ...
assert itemsAreLT9AndValid()
... more code here ...
This way, you've put all of your code into an assert statement. Of
course, (in my experience) 90% of all the debug code can be expressed as
a single boolean expression, so 90% of the time you won't need the
helper function, and you can just write something like this:
assert items > 9
but there are a few cases (like running multiple things or testing with
a loop) which are difficult or impossible to express without creating
the extra function to wrap it.
You'll probably want to enclose the definitions of ALL of the test
functions inside an "if debug:" (one which executes just once), so that
you don't even create the functions unless you need them. For instance,
the following:
... code here ...
def itemsAreLT9AndValid(items):
if items > 9:
print "fatal error..."
do_some_check_foo(42)
assert itemsAreLT9AndValid()
... more code here ...
would be a bad idea for performance reasons (we may not CALL the
function if debug is off, but we CREATE it each time.
-- Michael Chermside
More information about the Python-list
mailing list