Assertions are diagnostic predicates which must evaluate to Boolean true; otherwise, an exception is raised to indicate that the expression is false. These work similarly to the assert macros which are part of the C language preprocessor, but in Python these are runtime constructs (as opposed to pre-compile directives).
If you are new to the concept of assertions, no problem. The easiest way to think of an assertion is to liken it to a raise-if statement (or to be more accurate, a raise-if-not statement). An expression is tested, and if the result comes up false, an exception is raised.
Assertions are carried out by the assert statement, the newest keyword to Python, introduced in version 1.5.
The assert statement evaluates a Python expression, taking no action if the assertion succeeds (similar to a pass statement), but otherwise raises an AssertionError exception. The syntax for assert is:
assert expression [,arguments]
Here are some examples of the use of the assert statement:
assert 1 == 1 assert (2 + 2) == (2 * 2) assert len(['my list', 12]) < 10 assert range(3) == [0, 1, 2]
AssertionError exceptions can be caught and handled like any other exception using the try-except statement, but if not handled, they will terminate the program and produce a traceback similar to the following:
>>> assert 1 == 0 Traceback (most recent call last): File "<pyshell#85>", line 1, in <module> assert 1 == 0 AssertionError