assert is a statement in Python that is used to check whether a condition evaluates to
True or not. If not, it raises the
assert does nothing when the condition evaluates to
True, while it raises an exception when the condition evaluates to
>>> assert True >>> assert False Traceback (most recent call last): AssertionError
assert statement, you can also print an optional message for the condition that results in
>>> assert 1 == '1', 'Integers and numbers are different' Traceback (most recent call last): AssertionError: Integers and numbers are different
When to use assert in Python?
assert is useful in the following cases:
- To debug your code or detect errors early in your program. For example, a type error if not caught early, can go through several layers of code before actually raising an
- In documenting code for other programmers. For example, the programmer who sees
assertin the code can be sure that the condition will hold from now.
assert [condition] in Python is roughly equivalent to:
if not [condition]: raise AssertionError()