Although assert statements are a bit more streamlined, by themselves they're conditionals that raise exceptions when their expressions are false. It's a fair concern that using assert statements generously will leave code littered with extra conditional statements that will impact its performance. The assert statement relies on a built-in variable in Python,__debug_, which is True by default. That means the assert statement we used previously in assert_test.py is equivalent to if __debug__ :
But if the _debug_variable is False, no code will be generated at all for assert statements. The catch is that_debug_can't be directly assigned:
File "<stdin>", line 1 SyntaxError: assignment to keyword
To turn off the_debug_variable, either you need to have the PYTHONOPTIMIZE environment variable set, or you need to run Python with the -O option. When the
_debug_variable has been turned off with the -O parameter, the previous test using assert_test.py no longer gives an error:
>>> import assert_test
By using assert (and the_debug_variable), you can have several checks in place as you develop and test your code. And then, by giving Python a single option, you can have all of that testing code disappear for production runs but still be available the next time you need to debug.
Was this article helpful?