Python Reference ยท Exceptions
Python AssertionError
Reference for Python AssertionError: how a failed assert statement raises it, custom messages, the python -O switch, and when not to use assert.
AssertionError is raised when an assert statement finds its condition false. An assertion states something that must be true if your program is correct; if it is not, you have found a bug, and the program stops at that spot with a traceback.
assert condition, message is roughly shorthand for if __debug__ and not condition: raise AssertionError(message). The message is optional but makes the failure much easier to understand. You can also raise AssertionError by hand, and testing frameworks use it for failed checks.
assert 2 + 2 == 5, "arithmetic is broken" # AssertionError: arithmetic is broken
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. If its truth value is false, AssertionError is raised. |
message |
Optional expression, evaluated only on failure, and passed to AssertionError. |
Raises when: the condition is false and assertions are enabled (the default).
Usage notes
- Assertions can be switched off. Running
python -O(or-OO, or settingPYTHONOPTIMIZE) removesassertstatements entirely and sets__debug__toFalse. Never rely on an assertion for something that must always happen. - Not for input validation. Check arguments, user input and external data with
ifand raiseValueErrororTypeError. Use assertions only for internal sanity checks, invariants and "this can't happen" branches. - No side effects in the condition.
assert queue.pop() == 3would remove an item only when assertions are on. - Don't wrap the condition in parentheses with a message.
assert (x > 0, "message")is a non-empty tuple, which is always true, so it never fails. Recent Python versions warn about it with aSyntaxWarning. - Write messages that name the values, using an f-string; they are built only when the check fails, so they cost nothing on success.
- Catching it is unusual. If you must report a failure, catch
AssertionErrorat the top of a test or tool; otherwise let it end the program with its traceback. - Testing.
unittestprovides methods such asassertEqual()that give richer messages; pytest rewrites plainassertstatements to show the compared values. Both signal failure withAssertionError. - Use
raise AssertionError(...)ortyping.assert_never()for a branch that should be unreachable, since a plainassert Falseis removed under-O.
Related
assert,ValueError,TypeError- the exception hierarchy,
raise - Lessons: Testing, Debugging