if(debug), optimized away?
Bengt Richter
bokr at oz.net
Thu Jul 25 17:02:51 EDT 2002
On Thu, 25 Jul 2002 20:39:32 +0200, Yigal Duppen <yduppen at xs4all.nl> wrote:
>> 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?
>
>I doubt it.
>However, if you use the (predefined) __debug__, it does get optimized away
>(at least, I think so).
>
>if __debug__:
> # do stuff
>
>Note that you cannot set __debug__; it is always true, except when running
>python with the -O flag.
>
You are right:
[14:09] C:\pywk\junk>python -O
Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> __debug__
0
>>> __debug__=1
File "<stdin>", line 1
SyntaxError: can not assign to __debug__
>>> from miscutil import disex
>>> disex("""\
... if __debug__:
... a='debug'
... else:
... a='no debug'
... """)
0 LOAD_CONST 0 ('no debug')
3 STORE_NAME 0 (a)
6 LOAD_CONST 1 (None)
9 RETURN_VALUE
(disex is just a convenience thing of mine using compile and dis)
>Furthermore, for checks such as these it is better to use the 'assert'
>keyword. This too is removed when python -O is used.
>
>assert items > 9, "Fatal error, too many items"
>
Regards,
Bengt Richter
More information about the Python-list
mailing list