all Python 3Exceptionsconstruct
assert
checking
An assertion — checks a condition and raises AssertionError when it is False. Used for debugging and tests. Disabled with -O.
Syntax
assert condition, 'message'
The classic trap is an extra pair of parentheses: assert (x > 0, 'message') tests a non-empty tuple, which is always truthy, so the check silently never fires (you only get a syntax warning). And because python -O strips assertions entirely, they must not guard user input, permissions or anything coming from outside — use a plain if with raise for that; assert is for invariants that cannot break unless the code itself is wrong.
Examples
def divide(a, b):
assert b != 0, 'Denominator must not be zero'
return a / b
print(divide(10, 2)) # → 5.0
try:
divide(1, 0)
except AssertionError as e:
print(e) # → Denominator must not be zero
def get_positive(n):
assert isinstance(n, int) and n > 0, f'Expected positive int, got {n!r}'
return n
print(get_positive(5)) # → 5
def test_add():
assert 1 + 1 == 2
assert 'hello'.upper() == 'HELLO'
assert len([1,2,3]) == 3
test_add() # ничего не печатает — все assert верны
# assert с коллекцией
def first(lst):
assert len(lst) > 0, 'List is empty'
return lst[0]
print(first([10,20])) # → 10
# ВАЖНО: assert отключается при python -O
# Не используй для валидации входных данных в продакшн!
x = 10
assert x > 0 # только для разработки
See also
Open in the full glossarydocs.python.orgReport an inaccuracy