design of python: why is assert a statement and not a function? design of python: why is assert a statement and not a function? python python

design of python: why is assert a statement and not a function?


Are there any advantages to having assert be a statement (and reserved word) instead of a function?

  1. Cannot be reassigned to a user function, meaning it can be effectively disabled at compile time as @mgilson pointed out.
  2. The evaluation of the second, optional parameter is deferred until if/when the assertion fails. Awkward to do that with functions and function arguments (would need to pass a lambda.) Not deferring the evaluation of the second parameter would introduce additional overhead.


One of the wonderful things about assert in python and in other languages (specifically C) is that you can remove them to optimize your code by just adding the correct #define (optionally on the commandline with any compiler I've ever used) or optimization flags (-O in python). If assert became a function, this feature would be impossible to add to python as you don't know until runtime whether you have the builtin assert function or user-defined function of the same name.


Also note that in python, function calls are reasonably expensive. Replacing inline with the code if __debug__: ... is probably a lot more efficient than doing a function call which could be significant if you put an assert statement in a performance critical routine.


In addition to the other answers (and sort of off-topic) a tip. To avoid the use of backslashes you can use implicit line joining inside parenthesis. ;-)

Instead of:

assert some_long_condition, \       "explanation"

You could write:

assert some_long_condition, (       "explanation")