assert statement exists in almost every programming language. It has two main uses:
It helps detect problems early in your program, where the cause is clear, rather than later when some other operation fails. A type error in Python, for example, can go through several layers of code before actually raising an
Exceptionif not caught early on.
It works as documentation for other developers reading the code, who see the
assertand can confidently say that its condition holds from now on.
When you do…
… you’re telling the program to test that condition, and immediately trigger an error if the condition is false.
In Python, it’s roughly equivalent to this:
if not condition: raise AssertionError()
Try it in the Python shell:
>>> assert True # nothing happens >>> assert False Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError
Assertions can include an optional message, and you can disable them when running the interpreter.
To print a message if the assertion fails:
assert False, "Oh no! This assertion failed!"
Do not use parenthesis to call
assert like a function. It is a statement. If you do
assert(condition, message) you’ll be running the
assert with a
(condition, message) tuple as first parameter.
As for disabling them, when running
python in optimized mode, where
False, assert statements will be ignored. Just pass the
python -O script.py
See here for the relevant documentation.