assert statement
assert checks a condition that should always be true and stops with an AssertionError when it is not. Ideal for tests and sanity checks.
assert condition
assert condition, "message"assert total >= 0 says "at this point, total can never be negative". If the condition is true, nothing happens. If it is false, Python raises AssertionError, with your message if you gave one.
Use it to catch your own mistakes early: inside tests, and as quick sanity checks while developing. A failed assert points straight at the place where your assumption broke.
Asserts can be switched off: running Python with the -O option skips them all. So never use assert to check user input or anything security-related; use if plus raise statement for that.
Examples
1A passing and a failing assert
prices = [4.5, 3.0, 12.0]
assert len(prices) == 3
print("first check passed")
try:
assert all(p < 10 for p in prices), "a price is 10 or more"
except AssertionError as e:
print("AssertionError:", e)first check passed AssertionError: a price is 10 or more
2Simple tests for a function
Test tools such as pytest are built around plain assert lines like these.
def to_celsius(f):
return round((f - 32) * 5 / 9, 1)
assert to_celsius(32) == 0
assert to_celsius(212) == 100
assert to_celsius(98.6) == 37.0
print("all tests passed")all tests passed
3Sanity check inside a calculation
def split_bill(total, people):
share = round(total / people, 2)
assert share * people >= total - 0.05, "rounding lost too much"
return share
print(split_bill(100, 3))33.33
4A useful message
stock = {"pens": 5}
item, wanted = "pens", 8
try:
assert stock[item] >= wanted, f"only {stock[item]} {item} left, {wanted} wanted"
except AssertionError as e:
print(e)only 5 pens left, 8 wanted
Common mistakes
Putting brackets around condition and message
assert (x > 0, "must be positive") asserts a two-item tuple, which is always true, so it never fails. Python even warns about it. Write it without brackets: assert x > 0, "must be positive".
Validating user input with assert
With python -O every assert disappears, and the bad input gets through. Raise a real error instead.
def set_quantity(n):
if n < 1:
raise ValueError("quantity must be at least 1")
return n
try:
set_quantity(0)
except ValueError as e:
print("ValueError:", e)ValueError: quantity must be at least 1
Questions people ask
When should I use assert?
For things that can only be false if your own code has a bug: in tests, and as checks during development.
What is the difference between assert and raise?
assert is a shortcut for "raise AssertionError if this is false" and can be turned off. raise statement always runs and lets you choose the error type.
How do I write tests with assert?
Put assert lines in functions whose names start with test_ and run them with pytest.