Python for AI Engineers · Part A · Lesson 6 of 26
Python type hints and Pydantic validation
Type hints for a Java or JavaScript developer: list[str], dict[str, int], X | None, TypedDict and Literal, why Python never checks them, and how mypy does. Then Pydantic: validated models, clear errors, Field rules, JSON in and out, and validating an LLM's JSON reply.
⏱ 40 min3 exercises that check your codeRuns in your browser
By the end you can
- Write type hints for lists, dicts, optional values, fixed choices (
Literal) and dict shapes (TypedDict) - Explain why hints are not checked at run time, and catch type bugs before running with mypy
- Define a Pydantic
BaseModel, read itsValidationError, and add rules withField - Turn models into dicts and JSON and back (
model_dump,model_validate,model_validate_json) - Validate a model's JSON reply against a schema, the core of structured LLM output
1Type hints: the basics
A type hint goes after a name with a colon (question: str), and the return type goes after ->. It looks like TypeScript, and it plays the same role: it documents the code and lets tools find mistakes.
Collections say what they hold in square brackets: list[str] is Java's List<String>, dict[str, int] is Map<String, Integer>. Use the lowercase built-in names; the old List and Dict from typing are no longer needed.
int | None means "an int, or None" (like number | null in TypeScript). Optional[str] from typing is the older spelling of exactly the same thing, and you will still see it in a lot of code. Note that "optional" here means "can be None", not "can be left out": the = None default is what lets the caller skip the argument.
from typing import Optional
def build_prompt(question: str, context: list[str], max_chars: int | None = None) -> str:
text = "\n".join(context) + "\n\nQuestion: " + question
if max_chars is not None:
text = text[:max_chars]
return text
token_counts: dict[str, int] = {"system": 12, "user": 30}
last_error: Optional[str] = None # the older spelling of str | None
print(build_prompt("What is RAG?", ["RAG adds retrieved text to the prompt."]))
print(build_prompt("What is RAG?", ["RAG adds retrieved text."], max_chars=10))
print(sum(token_counts.values()), last_error)
print(build_prompt.__annotations__["max_chars"])
Expected output
RAG adds retrieved text to the prompt. Question: What is RAG? RAG adds r 42 None int | None
String buildPrompt(String question, List<String> context, Integer maxChars) { ... }
Map<String, Integer> tokenCounts = Map.of("system", 12, "user", 30);
String lastError = null; // any object type may be null in Java function buildPrompt(question: string, context: string[], maxChars: number | null = null): string { ... }
const tokenCounts: Record<string, number> = { system: 12, user: 30 };
let lastError: string | null = null; The last line shows where hints live: Python stores them on the function in __annotations__. Python itself does nothing with them, but libraries can read them at run time. That is exactly what Pydantic does later in this lesson.
2Hints are not enforced at run time
This is the biggest surprise for a Java developer. Python never checks a hint when the code runs. There is no compiler step: a wrong type goes straight into the function.
Sometimes that "works" and gives a wrong answer (two strings joined instead of two numbers added). Sometimes it fails later, deep inside the function, with an error that does not mention the hint at all.
def add_tokens(a: int, b: int) -> int:
return a + b
print(add_tokens(2, 3))
print(add_tokens("2", "3")) # wrong types, no error: strings are joined
def shout(text: str) -> str:
return text.upper() + "!"
try:
shout(42) # fails later, inside the function
except AttributeError as e:
print("AttributeError:", e)
Expected output
5 23 AttributeError: 'int' object has no attribute 'upper'
Watch out Data from outside your program (a model reply, a request body, a JSON file) has no types until you check it. A hint like score: int on data you just parsed is a wish, not a guarantee. Validate it with Pydantic (below).
3Shapes for dicts and fixed choices: TypedDict and Literal
Literal["system", "user", "assistant"] means "one of these exact values", like a TypeScript string union or a small Java enum. You can give it a name (Role = ...) and reuse it.
TypedDict describes the keys and value types of a dict. It is how you type the chat messages you send to an LLM API, which are plain dicts. It is like a TypeScript interface for an object literal.
Both are still only hints: a Message is an ordinary dict at run time, and nothing stops {"role": "admin"}. A type checker will catch it, as the next section shows.
from typing import Literal, TypedDict
Role = Literal["system", "user", "assistant"]
class Message(TypedDict):
role: Role
content: str
def to_prompt(messages: list[Message]) -> str:
return "\n".join(f"{m['role']}: {m['content']}" for m in messages)
history: list[Message] = [
{"role": "system", "content": "You are terse."},
{"role": "user", "content": "What is DNS?"},
]
print(to_prompt(history))
print(type(history[0])) # at run time it is a plain dict
Expected output
system: You are terse. user: What is DNS? <class 'dict'>
Tip Use TypedDict for dicts you pass to a library that wants dicts (message lists, JSON payloads). Use a dataclass or a Pydantic model when you own the object and want attribute access (m.role).
4Catch type bugs before running: mypy
A type checker reads your code without running it and reports where the hints are broken, like javac or tsc --noEmit. The two common ones are mypy and pyright (pyright also powers the Python type checks in VS Code, so your editor underlines these mistakes as you type).
This runs on your machine, not in the browser. In a uv project (lesson 1), save the file below as main.py. uv add --dev mypy installs mypy as a development tool (like a devDependency in npm), and uv run mypy main.py checks the file. Nothing in main.py is executed.
uv add --dev mypy
uv run mypy main.py main.py:14: error: Item "None" of "str | None" has no attribute "split" [union-attr] main.py:17: error: Argument 1 to "add_tokens" has incompatible type "str"; expected "int" [arg-type] main.py:17: error: Argument 2 to "add_tokens" has incompatible type "str"; expected "int" [arg-type] main.py:18: error: Incompatible types (expression has type "Literal['admin']", TypedDict item "role" has type "Literal['system', 'user', 'assistant']") [typeddict-item] Found 4 errors in 1 file (checked 1 source file)
from typing import Literal, TypedDict
class Message(TypedDict):
role: Literal["system", "user", "assistant"]
content: str
def add_tokens(a: int, b: int) -> int:
return a + b
def first_word(text: str | None) -> str:
return text.split()[0]
add_tokens("2", "3")
msg: Message = {"role": "admin", "content": "hi"} textmay beNone, andNonehas no.split(). mypy wants you to handle that case first, for exampleif text is None: return "".line 14- Strings passed where the hints say
int. Python would run this and return"23"; mypy reports it.line 17 "admin"is not one of the allowedLiteralvalues forrole.line 18
Each line is file:line: error: message [error code]. mypy exits with status 1 when it finds errors, so you can run it in CI and fail the build, just like a failing compile. To try pyright instead, run uvx pyright main.py (uvx runs a tool without adding it to the project); it reports the same four problems in its own wording.
Tip Functions without any hints are skipped by mypy by default. Hint at least the parameters and return type of every function you write, and the checker covers it.
5Pydantic: hints that are checked
Pydantic reads the hints on a class and checks every value when an object is created. Anything wrong raises an error right there, at the edge of your program, instead of deep inside it. It is the most used validation library in Python, and the OpenAI and Anthropic SDKs, FastAPI and LangChain are built on it. Think of it as Bean Validation (@NotNull, @Size) plus Jackson in one, or Zod in TypeScript.
A model is a class that inherits from BaseModel, with one hinted line per field. A field with a default is optional; a field without one is required. You create it with keyword arguments.
By default Pydantic also converts obvious values: the string "42" becomes the int 42, and 7.0 becomes 7. That is handy for JSON and form data, where numbers often arrive as strings.
uv add pydantic from pydantic import BaseModel
class User(BaseModel):
name: str
age: int
email: str | None = None # optional, defaults to None
u = User(name="Asha", age=31)
print(u)
print(u.name, u.age + 1)
v = User(name="Ben", age="42") # a numeric string is converted to int
print(v.age, type(v.age))
w = User(name="Chen", age=7.0) # a whole float is accepted too
print(w.age)
Expected output
name='Asha' age=31 email=None Asha 32 42 <class 'int'> 7
On your machine, uv add pydantic adds it to the project (Pydantic 2). In the browser editor it is already available, so just press Run.
Tip Conversion only goes where it is safe: "forty" or 3.5 for an int is an error (next section), and an int is not turned into a str. If you want no conversion at all, add model_config = ConfigDict(strict=True) to the class (import ConfigDict from pydantic).
6Reading a ValidationError
When data does not fit, Pydantic raises ValidationError. It collects every problem, not just the first, so one try tells you everything that is wrong.
e.errors() returns a list of dicts. The useful keys: loc (where: a tuple of field names and list indexes), type (a stable code such as missing or int_parsing that your code can check) and msg (a sentence for humans). e.error_count() gives how many there are.
If you print(e) you get the same information as a readable block, ending with a link to the docs for each error type.
from pydantic import BaseModel, ValidationError
class User(BaseModel):
name: str
age: int
try:
User(name="Dee", age="forty")
except ValidationError as e:
print(e.error_count(), "error")
for err in e.errors():
print(err["loc"], err["type"], "-", err["msg"])
try:
User(age=3.5)
except ValidationError as e:
for err in e.errors():
print(err["loc"], err["type"], "-", err["msg"])
Expected output
1 error
('age',) int_parsing - Input should be a valid integer, unable to parse string as an integer
('name',) missing - Field required
('age',) int_from_float - Input should be a valid integer, got a number with a fractional partTip These messages are written for a reader, and that includes an LLM. When a model returns bad JSON, sending these messages back and asking it to fix its answer works very well (last section).
7Rules on fields: Field and Literal
Field(...) adds rules to a field and can set its default. Numbers: gt (greater than), ge (greater or equal), lt, le. Strings and lists: min_length, max_length. A Literal type limits a field to fixed values.
The model below is a request to a chat model: the prompt must not be empty, the temperature must be between 0 and 2, and so on. All four broken rules are reported together.
from typing import Literal
from pydantic import BaseModel, Field, ValidationError
class ChatRequest(BaseModel):
model: str = "llama3.2:3b"
prompt: str = Field(min_length=1, max_length=50)
temperature: float = Field(default=0.7, ge=0, le=2)
max_tokens: int = Field(default=256, gt=0)
tags: list[str] = []
mode: Literal["chat", "json"] = "chat"
print(ChatRequest(prompt="Hi"))
try:
ChatRequest(prompt="", temperature=3, max_tokens=0, mode="xml")
except ValidationError as e:
for err in e.errors():
print(err["loc"][0], "-", err["msg"])
Expected output
model='llama3.2:3b' prompt='Hi' temperature=0.7 max_tokens=256 tags=[] mode='chat' prompt - String should have at least 1 character temperature - Input should be less than or equal to 2 max_tokens - Input should be greater than 0 mode - Input should be 'chat' or 'json'
tags: list[str] = [] looks like the mutable default trap from lesson 4, but it is safe here: Pydantic copies the default for every new object. In a plain function or dataclass it is still a bug.
8To JSON and back, and nested models
A field can be another model, or a list of them. Pydantic validates the whole tree and turns nested dicts into nested model objects.
Four methods cover the round trip. model_dump() gives a plain dict and model_dump_json() a JSON string (to send or store). Model.model_validate(d) builds a model from a dict, and Model.model_validate_json(s) from JSON text in one step: it parses and validates together, so you do not need json.loads first.
from pydantic import BaseModel
class Source(BaseModel):
title: str
page: int
class Answer(BaseModel):
text: str
confidence: float
sources: list[Source] = []
a = Answer(text="Paris", confidence=0.9, sources=[Source(title="Atlas", page=12)])
print(a.model_dump()) # a plain dict, nested models included
print(a.model_dump_json()) # a JSON string, ready to send or store
data = {"text": "Lyon", "confidence": "0.4", "sources": [{"title": "Guide", "page": "3"}]}
b = Answer.model_validate(data) # from a dict (for example parsed JSON)
print(b.sources[0].page + 1, type(b.sources[0]).__name__)
c = Answer.model_validate_json('{"text": "Nice", "confidence": 0.7}') # straight from JSON text
print(c.text, c.sources)
Expected output
{'text': 'Paris', 'confidence': 0.9, 'sources': [{'title': 'Atlas', 'page': 12}]}
{"text":"Paris","confidence":0.9,"sources":[{"title":"Atlas","page":12}]}
4 Source
Nice []ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(answer); // model_dump_json()
Answer b = mapper.readValue(json, Answer.class); // model_validate_json(json)
Map<String, Object> map = mapper.convertValue(answer, Map.class); // model_dump() Watch out Pydantic 1 used .dict(), .json() and parse_obj(). Old blog posts and answers still show them. In Pydantic 2 they are deprecated: use the model_ methods.
9Structured LLM output: validate the model's JSON
Ask a model for JSON and it usually complies, but not always: a value outside the allowed set, a number out of range, or a friendly sentence before the JSON. Your code must never trust the reply blindly. This is where everything in this lesson meets.
One Pydantic model does both jobs. model_json_schema() turns it into a JSON Schema you put in the prompt (or pass to an API's structured output option) to tell the model the exact shape. model_validate_json() then checks the reply against the same model. Either you get a typed object, or a list of precise errors.
Below, three fake replies stand in for a real model. Only the first is accepted.
from typing import Literal
from pydantic import BaseModel, Field, ValidationError
class Review(BaseModel):
sentiment: Literal["positive", "negative", "neutral"]
score: int = Field(ge=1, le=5)
summary: str = Field(max_length=60)
schema = Review.model_json_schema() # what you show the model
print(schema["properties"]["score"])
def parse_reply(reply: str) -> Review | None:
try:
return Review.model_validate_json(reply)
except ValidationError as e:
for err in e.errors():
print(" rejected:", err["loc"], err["msg"])
return None
replies = [
'{"sentiment": "positive", "score": 5, "summary": "Fast delivery"}',
'{"sentiment": "happy", "score": 9, "summary": "Great"}',
'Sure! Here is the JSON: {"sentiment": "neutral"}',
]
for reply in replies:
print(parse_reply(reply))
Expected output
{'maximum': 5, 'minimum': 1, 'title': 'Score', 'type': 'integer'}
sentiment='positive' score=5 summary='Fast delivery'
rejected: ('sentiment',) Input should be 'positive', 'negative' or 'neutral'
rejected: ('score',) Input should be less than or equal to 5
None
rejected: () Invalid JSON: expected value at line 1 column 1
NoneThe third reply fails as Invalid JSON with an empty loc, because the whole text is not JSON. In a real app you would send these error messages back to the model ("your JSON had these problems, try again") a limited number of times, and give up cleanly after that. You build exactly that loop in the Structured output lab.
Tip Keep the model small and strict: Literal for categories, Field limits for numbers and lengths. Every rule you add is one more kind of bad reply your code never has to handle.
Common mistakes
- Expecting Python to check hints at run time. It never does: use mypy or pyright before running, and Pydantic for data that comes from outside.
- Reading
Optional[str]as "can be left out". It means "can beNone"; the field or argument is only skippable if it also has a default (= None). - Calling
json.loadsand then trusting the dict. UseModel.model_validate_json(text)so the parse and the checks happen in one step. - Catching
ValidationErrorand printing only "invalid". Loge.errors(): thelocandmsgtell you (or the model) exactly what to fix. - Copying Pydantic 1 code (
.dict(),.json(),parse_obj,class Config). In Pydantic 2 usemodel_dump,model_dump_json,model_validateandmodel_config. - Forgetting that Pydantic converts by default:
"42"becomes42. Turn on strict mode where a string must stay an error.
Practice
Write the code, then press Check. Your work is saved in this browser.
1Hint a helper
count_roles already works: it counts how many messages each role has. Add type hints so that messages is a list of dicts from str to str, and the function returns a dict from str to int. (The tests read the hints from __annotations__.)
def count_roles(messages):
counts = {}
for m in messages:
counts[m["role"]] = counts.get(m["role"], 0) + 1
return counts
print(count_roles([{"role": "user", "content": "hi"}, {"role": "user", "content": "again"}]))
Hint
Parameter hints go after a colon, the return hint after `->` before the final colon: `def f(x: list[int]) -> str:`.
2Validate tool arguments
A model asks to call a weather tool with some JSON arguments. Finish WeatherArgs so that: city is a non-empty string (required); days is an int from 1 to 7, default 1; units is "c" or "f", default "c". Anything else must raise ValidationError.
from pydantic import BaseModel
class WeatherArgs(BaseModel):
city: str
days: int = 1
units: str = "c"
print(WeatherArgs.model_validate({"city": "Pune", "days": "3"}))
Hint
Use `Field(default=1, ge=1, le=7)` for days, `Field(min_length=1)` for city, and `Literal["c", "f"]` (from `typing`) as the type of units.
3An error report for the model
Write error_report(reply) that validates reply (JSON text) as an Answer. Return [] if it is valid. Otherwise return one string per error: the loc parts joined with dots, then ": ", then the msg. Example: "sources.1.page: Input should be a valid integer, unable to parse string as an integer". When loc is empty (the text is not JSON at all), use the word reply as the location.
from pydantic import BaseModel, ValidationError
class Source(BaseModel):
title: str
page: int
class Answer(BaseModel):
text: str
sources: list[Source]
def error_report(reply: str) -> list[str]:
# your code here
return []
print(error_report('{"text": "x", "sources": [{"title": "A", "page": "two"}]}'))
Hint
Catch `ValidationError as e` around `Answer.model_validate_json(reply)`. For each `err` in `e.errors()`, `".".join(str(p) for p in err["loc"])` builds the location (indexes are ints, so convert them with `str`). `x or "reply"` gives `"reply"` when `x` is empty.
Interview questions
Q1Does Python check type hints at run time?
No. Hints are stored in __annotations__ and ignored by the interpreter. A static checker such as mypy or pyright checks them without running the code, and libraries such as Pydantic read them at run time to validate data.
Q2What is the difference between `Optional[str]` and `str | None`?
None: they mean the same type, "a str or None". X | None is the newer syntax (Python 3.10+). Neither makes a value skippable; that needs a default such as = None.
Q3When would you use TypedDict, a dataclass, or a Pydantic model?
TypedDict to type plain dicts you pass to an API, with no run-time cost. A dataclass for your own internal objects whose data you already trust. A Pydantic model at the edges, wherever data comes from outside (HTTP bodies, config, files, LLM output) and must be validated and converted.
Q4What does Pydantic do when a field has the wrong type?
In the default lax mode it converts safe cases ("42" to 42, 7.0 to 7) and otherwise raises a ValidationError that lists every problem with its location, an error type code and a message. Strict mode turns off the conversion.
Q5How do you get reliable structured output from an LLM?
Describe the expected shape as a Pydantic model, send its JSON Schema (in the prompt or the API's structured output option), validate the reply with model_validate_json, and on ValidationError send the error messages back and retry a limited number of times. Never use the raw reply without validating it.