typestar

Nested models in Python

Models inside models, and lists of them, validated all the way down.

from pydantic import BaseModel, ValidationError


class Step(BaseModel):
    idx: int
    title: str


class Tour(BaseModel):
    slug: str
    steps: list[Step] = []


tour = Tour(slug="basics", steps=[{"idx": 0, "title": "Variables"},
                                  {"idx": 1, "title": "Strings"}])
print(len(tour.steps), tour.steps[0].title)
print(tour.model_dump())

try:
    Tour(slug="x", steps=[{"idx": "one", "title": "bad"}])
except ValidationError as exc:
    print(exc.errors()[0]["loc"])

How it works

  1. A nested model type validates the dict it is given.
  2. list[Model] validates every element.
  3. Errors report the full path to the offending field.

Keywords and builtins used here

The run, in numbers

Lines
22
Characters to type
444
Tokens
161
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 92 seconds.

Type this snippet

Step 4 of 5 in Pydantic models, step 4 of 19 in Web services & data access.

← Previous Next →