Python assert with message

Mateen Kiani

Mateen Kiani

Published on Mon Jul 28 2025·3 min read

python-assert-with-message

Introduction

As developers, we often rely on assertions to catch unexpected conditions early in our code. However, the power of assertions truly shines when paired with custom messages that clarify what went wrong.

Ever wondered how adding a simple message can save hours of debugging time?

By including descriptive messages with your assert statements, you turn plain checks into self-documenting guards. In the sections below, we'll explore how to write clear assertions, use them in testing, handle performance implications, and follow best practices to keep your code robust.

Understanding assert

The assert statement in Python is a tool for verifying assumptions in your code. Its syntax is:

assert condition, "optional message"

If condition is false, Python raises an AssertionError with the given message. Without a message, the error only tells you that an assertion failed, offering little context.

Tip: Assertions should not replace regular error handling. Use them to catch developer errors, not user input issues.

Adding custom messages

Custom messages give you insight into why an assertion failed. They can include variable values or descriptions:

def divide(a, b):
assert b != 0, f"Cannot divide {a} by zero"
return a / b

If b is zero, the error reads: AssertionError: Cannot divide 10 by zero

Instead of a generic failure, you know exactly what caused the problem. For guidelines on naming your functions clearly, see Python function naming conventions.

Using assert in tests

In testing frameworks like pytest, assertions form the backbone of test checks. You can write:

def test_add():
result = add(2, 3)
assert result == 5, "add(2, 3) should return 5"

When a test fails, pytest shows both the condition and your message, making failures easier to diagnose.

Note: pytest rewrites assert statements to provide more detail, but custom messages still improve clarity.

Performance and disabling asserts

Python can disable all assert statements when running optimized bytecode (python -O). The optimizer removes assert lines, so use assertions for development checks, not critical runtime logic.

python -O your_script.py

In this mode, any assert with side effects will be skipped. Keep your assertions free of important state changes.

Best practices

  • Keep messages clear and concise.
  • Include variable data for context.
  • Avoid side effects in assertions.
  • Use assertions for internal sanity checks, not input validation.
  • Regularly run code with -O to ensure no side effects vanish.

For common pitfalls and interview prep, check out Python interview questions.

Conclusion

Using assert with custom messages transforms vague failures into actionable insights. Whether you are writing simple scripts or large applications, thoughtful assertion messages speed up debugging and maintain code clarity. Next time you add an assertion, ask yourself: will this message help me or a teammate find the issue faster?

Embrace clear assertions, and keep your code honest and self-documenting.


Mateen Kiani
Mateen Kiani
kiani.mateen012@gmail.com
I am a passionate Full stack developer with around 4 years of experience in MERN stack development and 1 year experience in blockchain application development. I have completed several projects in MERN stack, Nextjs and blockchain, including some NFT marketplaces. I have vast experience in Node js, Express, React and Redux.