Definition
Python has built-in assert statement to use assertion condition in the program
Assert, a condition that should not be False.
- If the condition is False, then an AssertionError error is raised along with the exception message text.
- Expression can be any string or anything that produces a string.
Syntax of Assert
assert condition, expression
Some Examples
a = 11 assert(a < 10 ), 'a should not exceed 10'
Output
AssertionError: a should not exceed 10
In the above example, the assert condition,
x > 10
evalutes to be
False, and so it will raise the AssertionError with the specified message 'a should not exceed 10'
import sys assert ('linux' in sys. platform), 'This code runs on Linux only.'
Output
AssertionError: This code runs on Linux only.
When Use Assert Statement
- To inform developers about unrecoverable errors in a program.
- Python’s assert statement is a debugging aid, not a mechanism for handling run-time errors.
Don't Use Asserts for Data Validation
- Asserts can be turned off globally in the Python interpreter.For Docs Link
- When you pass a tuple as the first argument in an assert statement.
- The assertion always evaluates as true and therefore never fails.
With Simple assert, You can verify that
- A condition has been met
- Throw exceptions if it hasn't