Skip to content
Tutorials Center
My learning

Topics

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.

Python
assert total >= 0, "total must not be negative"

Try it

Python Passing and failing assertions

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.

Python Common mistakes

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

Python
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:

Python
if __debug__:
    if not condition:
        raise AssertionError(message)

Raises: AssertionError.

Usage notes

  • Removed with -O. Running python -O (or setting PYTHONOPTIMIZE) sets __debug__ to False and drops every assert. Never rely on one for security checks or argument validation.
  • Do not put side effects in the condition. assert queue.pop() stops working under -O because the call disappears.
  • Parentheses trap. assert (cond, "msg") tests a two-item tuple, which is always true. Write assert cond, "msg".
  • Good uses: internal invariants, post-conditions after a complex algorithm, and tests. Frameworks like pytest rewrite plain assert to 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 AssertionError in production code is a sign the check should be a normal exception instead.
  • For floats compare with math.isclose(), not ==.