Skip to content
Foxipa

Suggest an edit

Tell us what should be corrected, clarified, or improved. Submission will be connected to Foxipa’s contribution service later.

No information is sent anywhere yet. Your suggestion is only prepared in your browser.

Learning

Python Assert Statements

Learn how Python's assert statement checks assumptions and raises AssertionError when an expected condition is false, including when assert is appropriate and when explicit error handling is required.

Levels: Beginner, Intermediate ~12 min read

Basic

Sometimes a program reaches a point where a condition should already be true. Python's assert statement lets you state that assumption directly. If the condition is false, Python raises AssertionError.

The basic form

python basic.py
1
2
3
4
5
6
7
count = 4
assert count > 0
print("Count is valid")

name = "Ada"
assert name
print("Name is present")

When each condition is true, execution continues normally.

The expression after assert is evaluated. A true result lets the program continue. A false result causes an AssertionError to be raised.

A failed assertion

python failure.py
1
2
3
4
5
6
7
items = []

try:
    assert items, "items should not be empty"
except AssertionError as error:
    print(type(error).__name__)
    print(error)

A false assertion raises AssertionError, and the optional message becomes the exception's message.

The optional second expression supplies information when the assertion fails: assert condition, message. The message is evaluated only when the assertion fails.

Assert an internal assumption

python assumption.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
def first_item(items):
    assert items, "first_item expects a non-empty sequence"
    return items[0]

print(first_item([10, 20, 30]))

try:
    first_item([])
except AssertionError as error:
    print(error)

Assertions can document an assumption that the program expects to hold at a particular point.

This is most useful for assumptions about the program's own state or a programmer-facing invariant. It makes an unexpected state fail close to where the assumption was made.

Assert is not input validation

python validation.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
def set_age(age):
    if age < 0:
        raise ValueError("age must be non-negative")
    return age

try:
    set_age(-1)
except ValueError as error:
    print(type(error).__name__)
    print(error)

Use explicit error handling when invalid external input must be rejected, rather than relying on assert.

The distinction matters because Python can omit assert statements when optimization is requested. An input or configuration check should therefore use normal control flow and an explicit exception when it must always run.

The optional message

python message.py
1
2
3
4
5
6
7
limit = 10
value = 12

try:
    assert value <= limit, f"value {value} exceeds limit {limit}"
except AssertionError as error:
    print(error)

The comma form lets you attach a useful diagnostic message to a failed assertion.

Assertions and optimization

python debug-mode.py
1
2
3
4
print("assertions enabled:", __debug__)

assert __debug__
print("The assertion is active in this run")

Normally __debug__ is true. Python can disable assert statements when started with -O.

Python's reference semantics describe an assert statement as a debugging assertion. In normal execution, a failed assertion raises AssertionError. Under optimization with -O, Python sets __debug__ false and emits no code for assert statements.

A useful mental model

Think of assert as a statement that says, “At this point in the program, I expect this to be true.” It is a programmer-facing diagnostic tool, not a general-purpose way to handle bad input.

Was this page helpful?

Mark this learning resource complete to track your learning progress.