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.
Python code
11 linesdef 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
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
- Raise ValueError with a descriptive message for strict input validation
- 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
More from Errors & debugging
- Catch RecursionError and Fail Gracefully in Python easy
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert an Invariant After a Complex Transformation in Python easy
Keep learning
Related tutorials and quizzes for this topic.