Pydantic models (BaseModel)
A Pydantic model is a class that describes the shape of some data and validates it when you create an object.
Used in 25 lessons of the course, from 01.04.
A Pydantic model is a class that inherits from BaseModel. Inside it you declare fields with type hints, like name: str.
When you create the object with keyword arguments, Pydantic checks each value. If it can, it converts the value to the declared type ("5" becomes 5 in an int field). If it can't, it raises a ValidationError.
Why write it this way? Data that comes from outside, like a language model's reply, can't be trusted. The model states once what you expect, and you get an object with attributes you can use with confidence.
In the course you'll see class EventDetails(BaseModel): to describe the event data the model must return. You write the fields; Pydantic does the validation.
class Point(BaseModel):
x: int
y: int
Reach for it when: you need data to have specific fields and types, especially if it comes from outside your code.
Examples
Common mistake
from pydantic import BaseModel
class Point(BaseModel):
x: int
y: int
Point(x="hola", y=2)Why: "hola" can't be converted to `int`, so Pydantic rejects the value.
How to write it: Pass a value that fits the type, or catch ValidationError with try / except.
Common mistake
from pydantic import BaseModel
class Point(BaseModel):
x: int
y: int
Point(1, 2)Why: A model only accepts keyword arguments, not positional values.
How to write it: Write Point(x=1, y=2).
