In Python, assert is an instruction, not a function. Was this a deliberate decision? Are there any advantages to assert being an expression (and a reserved word) instead of a function?
According to docs , assert expression1, expression2 expands to
if __debug__: if not expression1: raise AssertionError(expression2)
The docs also say that "the current code generator does not generate code for the assert statement when requesting optimization at compile time." Without knowing the details, it seems that in order to make this possible, a special case was required. But then a special case could also be used to optimize calls to assert() .
If assert was a function, you could write:
assert(some_long_condition, "explanation")
But since assert is an operator, the tuple always evaluates True and you get
SyntaxWarning: assertion is always true, perhaps remove parentheses?
The correct way to write:
assert some_long_condition, \ "explanation"
which is perhaps less cute.
python assert language-design
cberzan Nov 15 '12 at 1:45 2012-11-15 01:45
source share