Course map
Stage 1: Foundations
Stage 2: Data Integration
Stage 3: Building & Shipping
Stage 4: Customer Engagement
Stage 5: Specialization

Part 06 / Topic 5 of 7

Validation with Pydantic

Cleaning makes data tidy; validation makes it trustworthy. A Pydantic model is a schema as executable contract — every record either conforms or produces a precise error:

# examples/02_validate_every_record_with_pydantic_and.py
import csv, io
from datetime import date
from typing import Literal
from pydantic import BaseModel, Field, ValidationError, field_validator
from fdelab import SHIPMENTS_CSV

class Shipment(BaseModel):
    shipment_id: str = Field(pattern=r"^S-\d{4}$")
    customer: str
    weight_kg: float = Field(gt=0)
    status: Literal["delivered", "in_transit", "delayed"]
    shipped_on: date

    @field_validator("customer")
    @classmethod
    def strip(cls, v):
        return v.strip()

def to_kg(raw):
    if not raw.strip():
        return None
    num, unit = raw.split()
    return float(num) * (0.45359237 if unit.lower().startswith("lb") else 1.0)

good, quarantine = [], []
for row in csv.DictReader(io.StringIO(SHIPMENTS_CSV)):
    try:
        good.append(Shipment(shipment_id=row["shipment_id"], customer=row["customer"],
                             weight_kg=to_kg(row["weight"]),
                             status=row["status"].strip().lower().replace(" ", "_"),
                             shipped_on=row["shipped_on"].replace("/", "-")))
    except ValidationError as e:
        quarantine.append((row["shipment_id"], e.errors()[0]["loc"][0], e.errors()[0]["msg"]))

print("valid:", len(good), "(the duplicate S-1003 is valid; the load step removes it by upserting on id)")
print("S-1002 has the ambiguous date 03/02/2025 and stays quarantined until Acme confirms the format")
for q in quarantine:
    print("quarantined:", q)
# valid: 5 (the duplicate S-1003 is valid; the load step removes it by upserting on id)
# S-1002 has the ambiguous date 03/02/2025 and stays quarantined until Acme confirms the format
# quarantined: ('S-1002', 'shipped_on', 'Input should be a valid date or datetime, invalid character in year')
# quarantined: ('S-1004', 'weight_kg', 'Input should be a valid number')
# quarantined: ('S-1006', 'weight_kg', 'Input should be greater than 0')

Notice what the schema caught that cleaning alone would not: the negative weight (gt=0) and the missing weight — and that this stricter pass quarantines the ambiguous date rather than assuming a format. The two examples disagree on S-1002 deliberately: the pandas pass assumed month-first to show the mechanics; the validating pass holds the row until Acme confirms. In a real engagement, the second behaviour is the one you ship.

Done here? The practice set for Part 6 — 4 exercises with solutions — is on the part page.

Search the guide