In Python, assert
is a statement, and not a function.
According to the docs, assert expression1, expression2
is equivalent to
if __debug__:
if not expression1:
raise AssertionError(expression2)
The docs also say
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 on multiple lines is
assert some_long_condition, \
"explanation"
Why this decision? Are there advantages to having assert
as a statement (and a reserved word) instead of a function?
Are there any advantages to having assert be a statement (and reserved word) instead of a function?