Day 2:Static Type Hints (`typing`) & Runtime Data Validation with Pydantic v2
Battle-tested daily lesson note • 100% runnable code, interview Q&A, test suite & interactive quiz
Week 2 — Day 2: Static Type Hints (typing) & Runtime Data Validation with Pydantic v2
Mentor's Note (10+ YOE Staff AI Engineer POV): If you ask any Staff AI Engineer at OpenAI, Anthropic, or Google: "What is the #1 most important Python library in AI Engineering besides the LLM SDK itself?" Their answer is Pydantic v2.
Why? Python's built-in type hints (
def analyze(tokens: int)) are ignored at runtime! If an LLM returns{"tokens": "one hundred"}or{"covered_by_doc": true, "cited_section": "None"}(a logical contradiction!), standard Python happily accepts it until your database or frontend crashes 50 lines later. Pydantic v2 (powered bypydantic-corewritten in Rust) validates data at the exact microsecond it enters your system, generates JSON Schemas for LLM Structured Outputs / Tool Calling, and rejects invalid or contradictory LLM responses automatically!
Part 1: Static Type Hints (typing) vs Runtime Validation (pydantic)
1.1 Essential Modern Python Type Hints (Python 3.10–3.13+)
| Type Annotation | Meaning | AI Engineering Example |
|---|---|---|
str | None | Either a str or None (replaces Optional[str]) | error_message: str | None = None |
list[float] | A list of floats | embedding_vector: list[float] |
dict[str, Any] | Dictionary with string keys and any value | json_payload: dict[str, Any] |
Literal["CRITICAL", "WARNING", "INFO"] | Value MUST be one of these exact strings! | severity: Literal["CRITICAL", "WARNING", "INFO"] |
Protocol | Structural Subtyping ("Duck Typing" interface) | Defining an LLMProvider interface so OpenAI, Gemini, and Mock classes are interchangeable! |
1.2 The Shocking Truth: Python Does NOT Enforce Type Hints at Runtime!
def add_tokens(a: int, b: int) -> int:
return a + b
# Python runs this WITHOUT error and returns "100200" (string concatenation!) instead of 300!
add_tokens("100", "200")
To enforce types at runtime on external API / LLM inputs, we use Pydantic v2!
Part 2: Pydantic v2 Architecture & Lifecycle
[Raw LLM JSON String]
│
▼ Model.model_validate_json(raw_str)
[Rust Core (`pydantic-core`)] ──> 1. Parse JSON & Coerce/Check Field Types (`Field(ge=0, min_length=1)`)
│
▼
[@field_validator] ──> 2. Custom Single-Field Rules (e.g., strip whitespace, check prefix)
│
▼
[@model_validator(mode="after")] ─> 3. Cross-Field Logic! (e.g., if `covered_by_doc=True`, `cited_section` CANNOT be "None"!)
│
├──(Valid)────> Returns Type-Safe Python Object (`.model_dump()`, `.model_dump_json()`)
└──(Invalid)──> Raises `pydantic.ValidationError` with exact field path & reason!
2.1 Pydantic v1 vs Pydantic v2 Cheat Sheet (Interview Alert!)
Many older tutorials online (and even some LLM training data!) accidentally use deprecated Pydantic v1 methods. Memorize this table so you never write legacy v1 code in an interview:
| Operation | Deprecated Pydantic v1 | Modern Pydantic v2 (Rust-powered, 5x–50x faster!) |
|---|---|---|
Convert Model dict | obj.dict() | obj.model_dump() |
Convert Model JSON str | obj.json() | obj.model_dump_json(indent=2) |
Validate dict Model | Model.parse_obj(data) | Model.model_validate(data) |
Validate JSON str Model | Model.parse_raw(json_str) | Model.model_validate_json(json_str) |
| Export JSON Schema for LLM | Model.schema() | Model.model_json_schema() |
| Field Validator Decorator | @validator("field") | @field_validator("field") |
| Cross-Field Model Validator | @root_validator | @model_validator(mode="after") |
Part 3: Hands-On Lab — Building Our Month 1 Capstone Schema (schema_validator.py)
Look at src/schema_validator.py (in Tab 2: Codes — click Run in Browser to execute). We implement the exact RunbookResponse Pydantic v2 schema required by our Month 1 Capstone Blueprint, plus a cross-field @model_validator(mode="after") that catches a sneaky LLM hallucination:
- What if the LLM claims
"covered_by_doc": true, but sets"cited_section": "None"or""? - Our
@model_validatorimmediately catches that contradiction and raises aValidationErrorso the retry loop can ask the LLM to fix its citation!
Run Day 2 Code & Tests:
python week02_advanced_python_pydantic_asyncio_tests/day02_type_hints_and_pydantic_v2/src/schema_validator.py
python -m unittest discover -s week02_advanced_python_pydantic_asyncio_tests/day02_type_hints_and_pydantic_v2/tests -v