Python Reference ยท Statements and Keywords
The assert statement
Reference for the Python assert statement: check conditions while developing, add messages, understand python -O and why assert is not input validation.
The assert statement checks that a condition is true. If it is, nothing happens. If it is false, Python raises AssertionError, optionally with a message you provide. Assertions document and enforce things the programmer believes must always hold, such as "this list is never empty here".
They are a debugging aid, not a way to validate user input. When Python runs with the -O flag, assert statements are removed entirely.
assert total >= 0, "total must not be negative"
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
assert condition assert condition, message
| Part | Description |
|---|---|
condition |
Any expression. It is tested for truth. |
message |
Optional expression. Evaluated only if the assertion fails; its value is passed to AssertionError. |
The statement behaves like this code, which is skipped when optimization is on:
if __debug__: if not condition: raise AssertionError(message)
Raises: AssertionError.
Usage notes
- Removed with
-O. Runningpython -O(or settingPYTHONOPTIMIZE) sets__debug__toFalseand drops everyassert. Never rely on one for security checks or argument validation. - Do not put side effects in the condition.
assert queue.pop()stops working under-Obecause the call disappears. - Parentheses trap.
assert (cond, "msg")tests a two-item tuple, which is always true. Writeassert cond, "msg". - Good uses: internal invariants, post-conditions after a complex algorithm, and tests. Frameworks like pytest rewrite plain
assertto show detailed value diffs. - Bad uses: checking user input, file contents, network data or anything an outside caller could get wrong on purpose.
- Give a message when the failing expression alone would not explain what went wrong, for example
assert x > 0, f"x was {x}". - Catching
AssertionErrorin production code is a sign the check should be a normal exception instead. - For floats compare with
math.isclose(), not==.
Related
raise,try,AssertionErrormathmodule- Lessons: Testing, Debugging