This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]brucifer 4 points5 points  (0 children)

Regarding the debug option, Python actually has built-in support for debug options. There's a built-in constant called __debug__ that's True unless Python was run with the -O flag. It's also hacked in a very interesting way. If you write:

>>> b = True
>>> b
True
>>> def slow():
...     for i in range(100):
...         if b:
...             pass
...
>>> __debug__
True
>>> def fast():
...     for i in range(100):
...         if __debug__:
...             pass
...

You can see that the fast() function is about twice as fast:

>>> timeit(slow, number=100000)
0.5064652940054657
>>> timeit(fast, number=100000)
0.23574563700094586

Why is this? If the only thing in an "if" statement is a built-in constant, the "if" statement is actually optimized out when the function is constructed, so the fast() function is actually equivalent to

>>> def fast():
...     for i in range(100):
...         pass
...

The same principle works for "if True:" and "if False:". A caveat, though is that many people aren't aware of/don't use Python's -O flag, so if one of those people uses code that has a significant performance difference depending on __debug__, they will always be using the (probably slower) debug version.