How to Assert Preconditions with Descriptive Messages in Python

Use Python's assert statement with a custom message to validate function preconditions and fail fast with clear diagnostics.

Easy Python 3.9+ Aug 9, 2026 Errors & debugging 15 views 0 copies

Python code

11 lines
Python 3.9+
def divide(dividend, divisor):
    assert divisor != 0, f"Divisor must be non-zero, got {divisor!r}"
    return dividend / divisor


if __name__ == "__main__":
    print(divide(10, 2))
    try:
        divide(10, 0)
    except AssertionError as e:
        print(f"AssertionError: {e}")

Output

stdout
5.0
AssertionError: Divisor must be non-zero, got 0

How it works

The assert statement evaluates a condition and raises AssertionError when the condition is False. By appending a comma and a string, you provide a custom message that appears in the traceback, making failures easier to debug. In this example, divisor != 0 is the precondition; when called with 0, the assertion fails and the custom message includes the actual value using an f-string. This pattern is lightweight and ideal for catching programming errors early during development. However, assert statements are stripped when Python runs with the -O (optimize) flag, so use them for internal invariants, not for input validation that must always run.

Common mistakes

  • Using assert for user input validation, which can be disabled with -O
  • Assuming assert always runs and uses it for security checks
  • Forgetting that assert exceptions are AssertionError, not ValueError
  • Overusing assert for complex conditions that obscure the code

Variations

  1. Raise ValueError with a descriptive message for strict input validation
  2. Use the `warnings` module to log a warning instead of stopping execution

Real-world use cases

  • Validating function arguments at the start of a library call, like checking an index is within bounds.
  • Ensuring that a loaded configuration value meets expected types before processing it in a script.
  • Guarding internal state in a class method that must not be called before initialization.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Errors & debugging

Related tutorials and quizzes for this topic.