Errors
Assertions
assert checks an internal assumption. If the condition is false, Python raises AssertionError with an optional message.
Use assertions for programmer assumptions, not for validating user input or external data. Input validation should raise ordinary exceptions that production code expects to handle.
Assertions make invariants executable while keeping the successful path compact.
When the assertion is true, execution continues normally. The assertion documents the function's internal expectation.
Source
def average(scores):
assert scores, "scores must not be empty"
return sum(scores) / len(scores)
print(average([8, 10]))Output
9.0When the assertion is false, Python raises AssertionError. This signals a broken assumption, not a normal recovery path.
Source
try:
average([])
except AssertionError as error:
print(error)Output
scores must not be emptyNotes
- Use
assertfor internal invariants and debugging assumptions. - Use explicit exceptions for user input, files, network responses, and other expected failures.
- Assertions can be disabled with Python optimization flags, so do not rely on them for security checks.
See also
- alternative: Exceptions
- related: Custom Exceptions
- next depth: Type Hints
Run the complete example
Expected output
9.0
scores must not be empty
Execution time appears here after you run the example.