AI engineering glossary · Python advanced
What is pydantic?
Pydantic: A widely used Python library that validates and converts data according to type hints, defining models as classes. It is popular in web APIs and for parsing LLM structured outputs into checked objects.
Pydantic: an example
class User(BaseModel): age: int; User(age='25') converts the string to 25, while age='abc' raises a validation error.
Pydantic in Python
A short example you can run (Python 3.11). The output below is what it really prints.
from pydantic import BaseModel, ValidationError
class Invoice(BaseModel):
number: str
amount: float
gst_rate: float = 18.0
print(Invoice.model_validate({"number": "INV-7", "amount": "1500"}))
try:
Invoice.model_validate({"number": "INV-8", "amount": "fifteen hundred"})
except ValidationError as e:
print(e.errors()[0]["loc"], e.errors()[0]["type"])Output
number='INV-7' amount=1500.0 gst_rate=18.0
('amount',) float_parsingRelated terms
More Python advanced terms
Where you learn it
Pydantic is part of the AI Engineering Program, which teaches it with notes, a hands-on lab and an exam. The first lesson is free.