Assertions vs validator contracts
Intermediate
Defensive APIs: validation, sanitization & exceptions
Created by Pavel
· 29.04.2026 at 19:10 UTC
assert condition documents internal invariants you believe should already hold: “this tensor is 2-D after reshape,” “this index is inside bounds after my own logic.” Under python -O, assertions are stripped—they must never be the only guard on hostile input from the network.
Validators at IO boundaries assume the opposite: input is untrusted until proven. Pydantic @field_validator, manual checks on CSV columns, and SQL parameter binding all live in that layer.
Rule of thumb: assert things your own functions guarantee; validate things users and upstream systems supply.
Assertions reference: [1].
Sources
University approvals: 0
Tasks
Card Info
- Topic: Defensive APIs: validation, sanitization & exceptions
- Difficulty: Intermediate
- Completed: 0 users
Creator
Pavel