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
Question 1

Using bare assert as the only check that a raw HTTP query parameter is a positive integer is unwise mainly because:

Hint

Optimised bytecode may drop asserts.

Question 2

Where should you validate that learning_rate from a JSON config is a float in (0, 1]?

Hint

Trust boundaries.

Question 3

only_digits(s: str) -> str: keep only digit characters; if result empty, ValueError.

Hint

Filter with str.isdigit().

Starter code is prefilled; replace TODO blocks with your solution.
1 test case will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Card Info
  • Topic: Defensive APIs: validation, sanitization & exceptions
  • Difficulty: Intermediate
  • Completed: 0 users
Creator
Pavel
Pavel