Pydantic
tags :
Python Apps #
URL Pydantic is the most widely used data validation library for Python.
github Data validation using Python type hints
Installing Pydantic is as simple as: pip install pydantic
from pydantic import BaseModel
class MyModel(BaseModel):
a: int
b: list[str]
m = MyModel(a=123, b=['a', 'b', 'c'])
print(m.model_dump())
#> 'a': 123, 'b': ['a', 'b', 'c']
Why use Pydantic? #
Powered by type hints #
— with Pydantic, schema validation and serialization are controlled by type annotations; less to learn, less code to write and integration with your IDE and static analysis tools.
Speed #
— Pydantic’s core validation logic is written in Rust, as a result Pydantic is among the fastest data validation libraries for Python.
JSON Schema #
— Pydantic models can emit JSON Schema allowing for easy integration with other tools.
Strict and Lax mode #
— Pydantic can run in either strict=True mode (where data is not converted) or strict=False mode where Pydantic tries to coerce data to the correct type where appropriate.
Dataclasses, TypedDicts and more #
— Pydantic supports validation of many standard library types including dataclass and TypedDict.
Customisation #
— Pydantic allows custom validators and serializers to alter how data is processed in many powerful ways.
Ecosystem #
— around 8,000 packages on PyPI use Pydantic, including massively popular libraries like
- FastAPI,
- huggingface/transformers (Hugging Face)
- django-ninja
- SQLModel, and
- LangChain
Battle tested #
— Pydantic is downloaded >70m times/month and is used by all FAANG companies and 20 of the 25 largest companies on NASDAQ — if you’re trying to do something with Pydantic, someone else has probably already done it.