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.
assert statement takes an expression and optional message. assert statement is used to check types, values of argument and the output of the function. assert statement is used as debugging tool as it halts the program at the point where an error occurs.
That an “Assert” is used only for validations, where an “If” clause is used for the logic within our code. We can use an “If” clause to determine whether our automation should follow one path or another, but an “Assert” statement to validate the elements within those paths.
The assert() function tests the condition parameter. If it is false, it prints a message to standard error, using the string parameter to describe the failed condition.
An assertion is a statement in the Java programming language that enables you to test your assumptions about your program. For example, if you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than the speed of light.
Are there any advantages to having assert be a statement (and reserved word) instead of a function?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With