I have been reading some source code and in several places I have seen the usage of
What does it mean exactly? What is its usage?
assert statement exists in almost every programming language. It helps detect problems early in your program, where the cause is clear, rather than later as a side-effect of some other operation.
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.
Watch out for the parentheses. As has been pointed out above, in Python 3,
assert is still a statement, so by analogy with
print(..), one may extrapolate the same to
raise(..) but you shouldn't.
This is important because:
assert(2 + 2 == 5, "Houston we've got a problem")
won't work, unlike
assert 2 + 2 == 5, "Houston we've got a problem"
The reason the first one will not work is that
bool( (False, "Houston we've got a problem") ) evaluates to
In the statement
assert(False), these are just redundant parentheses around
False, which evaluate to their contents. But with
assert(False,) the parentheses are now a tuple, and a non-empty tuple evaluates to
True in a boolean context.