68

In Python, assert is a statement, and not a function. Was this a deliberate decision? Are there any advantages to having assert be a statement (and reserved word) instead of a function?

According to the docs, assert expression1, expression2 is expanded to

if __debug__:
    if not expression1: raise AssertionError(expression2)

The docs also say that "The current code generator emits no code for an assert statement when optimization is requested at compile time." Without knowing the details, it seems like a special case was required to make this possible. But then, a special case could also be used to optimize away calls to an assert() function.

If assert were a function, you could write:

assert(some_long_condition,
       "explanation")

But because assert is a statement, the tuple always evaluates to True, and you get

SyntaxWarning: assertion is always true, perhaps remove parentheses?

The correct way to write it is

assert some_long_condition, \
       "explanation"

which is arguably less pretty.

nicael
  • 18,550
  • 13
  • 57
  • 90
cberzan
  • 2,009
  • 1
  • 21
  • 32
  • 8
    It's somewhat surprising that this wasn't converted to a function with [`print`](http://stackoverflow.com/a/7020524/78845). Although, I prefer not to use raw `assert` statements. I only use `unittest.TestCase.assertTrue()`, and friends in test code and keep production code assertion-free. – johnsyweb Nov 15 '12 at 01:51
  • 1
    I use to throw `AssertionError` when parameters are technically valid but some non-trivial assumption regarding them (and usually other parts of environment) does not stand. Provided there is no better category, of course. – ivan_pozdeev Nov 15 '12 at 02:17

4 Answers4

41

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.
vladr
  • 65,483
  • 18
  • 129
  • 130
  • I wouldn't say "more easily disabled" since in the case where `assert` is a function, I think it would be impossible to optimize away :). – mgilson Nov 15 '12 at 02:24
  • @mgilson you're right, darn elections just over, I must have misspoken. ;) But kidding aside yes, you're absolutely right. – vladr Nov 15 '12 at 02:45
  • 3
    I hadn't though of the second point you raised (get it? raised? since assertions `raise AssertionError`?). +1 for that. – mgilson Nov 15 '12 at 02:47
  • 2
    Just want to add one more point, as mentioned in my another answer: it is not only the 2nd optional parameter is deferred. The first parameter is also deferred so that it will only be evaluated if it is in debug mode – Adrian Shum Mar 03 '15 at 01:25
21

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.

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • I'm confused by your statement that "the (CPython) code generator doesn't remove assert statements (currently)". From the docs, it seems like it does remove the statements (emits no code for them) if you turn optimization on. Am I misunderstanding? – cberzan Nov 15 '12 at 16:54
  • @cberzan -- You're correct. I didn't see your comment until just now, but it looks like python does remove them with the proper optimization flags turned on. I've edited to remove that error. (Thanks!) – mgilson Dec 11 '12 at 22:23
10

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")
siebz0r
  • 18,867
  • 14
  • 64
  • 107
8

I am no expert in Python, but I believe performance is one of the biggest reason.

if we have assert(expression, explanation) as function, if expression is expensive to evaluate, even we are in non-debug mode, Python needs to evaluate both expression to pass it to the assert function.

By expanding the assert, the expression and explanation statement is in fact not evaluated unless they are really needed (when debug evaluates to true). I believe it is critical if we want to make assert not affecting performance when not necessary (i.e. no performance hit in production system).

Adrian Shum
  • 38,812
  • 10
  • 83
  • 131
  • Why is it hard to make a function evaluate to a nop or something if debug evaluates to false? – rasen58 Apr 23 '18 at 13:27
  • @rasen58 I am not saying the function itself, but the EXPRESSION that we passed as parameter of assert. You cannot make them noop because Python is not lazy-evaluated. Of course you could delay the expression evaluation by changing it to a lambda and evaluate it in the function only if it is non-debug. However this is not the choice taken (I believe assert is available earlier than lambda, and using lambda here could be verbose) – Adrian Shum Jul 03 '19 at 02:43