04.05

TypeAdapter and discriminated unions

skillmaxingPython with AITypeAdapter and discriminated unions
Visual lesson

TypeAdapter and discriminated unions

Included with Pro · 4:33
Lessons · 977 words

Not everything you validate is a model. A database query returns a list of rows, a queue delivers a dictionary keyed by id, a streaming endpoint emits lines that are one of several shapes. TypeAdapter gives any type hint the same validate_python, validate_json, dump_json, and json_schema methods a model has, so you do not need a wrapper class whose only field is items.

The second idea in this lesson is what to do when a value can be one of several models. A plain union makes Pydantic try each member in turn and pick the best fit, which is slow and produces vague errors. A discriminated union names one field, usually type, that says which model applies, so validation is a single dictionary lookup and an error points at the right model.

Pro

Continue reading

Pro unlocks every video lesson, the full notes and runnable code across the Python with AI course, from the language itself to agents, MCP, Langfuse and deployment.

Unlock full access to
Python with AIAI researchComplete system design
30% off with LAUNCH30ends in 7h 40m
Buy now
View all plans ·Already Pro? Sign in
124 online