Index
{{ version }}.
Pydantic is the most widely used data validation library for Python.
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']}
- 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=Truemode (where data is not converted) orstrict=Falsemode 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
dataclassandTypedDict. - 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, 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.
Installing Pydantic is as simple as: pip install pydantic
To see Pydantic at work, let’s start with a simple example, creating a custom class that inherits from BaseModel:
from datetime import datetime
from pydantic import BaseModel, PositiveInt
class User(BaseModel):
id: int # (1)
name: str = 'John Doe' # (2)
signup_ts: datetime | None # (3)
tastes: dict[str, PositiveInt] # (4)
external_data = {
'id': 123,
'signup_ts': '2019-06-01 12:22', # (5)
'tastes': {
'wine': 9,
b'cheese': 7, # (6)
'cabbage': '1', # (7)
},
}
user = User(**external_data) # (8)
print(user.id) # (9)
#> 123
print(user.model_dump()) # (10)
"""
{
'id': 123,
'name': 'John Doe',
'signup_ts': datetime.datetime(2019, 6, 1, 12, 22),
'tastes': {'wine': 9, 'cheese': 7, 'cabbage': 1},
}
""" id is of type int; the annotation-only declaration tells Pydantic that this field is required. Strings,
bytes, or floats will be coerced to ints if possible; otherwise an exception will be raised.
name is a string; because it has a default, it is not required.
signup_ts is a datetime field that is required, but the value None may be provided;
Pydantic will process either a unix timestamp int (e.g. 1496498400) or a string representing the date and time.
tastes is a dictionary with string keys and positive integer values. The PositiveInt type is shorthand for Annotated[int, annotated_types.Gt(0)].
The input here is an ISO8601 formatted datetime, Pydantic will convert it to a datetime object.
The key here is bytes, but Pydantic will take care of coercing it to a string.
Similarly, Pydantic will coerce the string '1' to an integer 1.
Here we create instance of User by passing our external data to User as keyword arguments
We can access fields as attributes of the model
We can convert the model to a dictionary with model_dump()
If validation fails, Pydantic will raise an error with a breakdown of what was wrong:
from datetime import datetime
from pydantic import BaseModel, PositiveInt, ValidationError
class User(BaseModel):
id: int
name: str = 'John Doe'
signup_ts: datetime | None
tastes: dict[str, PositiveInt]
external_data = {'id': 'not an int', 'tastes': {}} # (1)
try:
User(**external_data) # (2)
except ValidationError as e:
print(e.errors())
"""
[
{
'type': 'int_parsing',
'loc': ('id',),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'not an int',
'url': 'https://errors.pydantic.dev/2/v/int_parsing',
},
{
'type': 'missing',
'loc': ('signup_ts',),
'msg': 'Field required',
'input': {'id': 'not an int', 'tastes': {}},
'url': 'https://errors.pydantic.dev/2/v/missing',
},
]
""" The input data is wrong here — id is not a valid integer, and signup_ts is missing
User(...) will raise a ValidationError with a list of errors
Hundreds of organisations and packages are using Pydantic. Some of the prominent companies and organizations around the world who are using Pydantic include:
For a more comprehensive list of open-source projects using Pydantic see the list of dependents on github, or you can find some awesome projects using Pydantic in awesome-pydantic.
<!— ## Discussion of Pydantic
Podcasts and videos discussing Pydantic.
Talk Python To Me{target=_blank} : Michael Kennedy and Samuel Colvin, the creator of Pydantic, dive into the history of Pydantic and its many uses and benefits.
Podcast.__init__{target=_blank} : Discussion about where Pydantic came from and ideas for where it might go next with Samuel Colvin the creator of Pydantic.
Python Bytes Podcast{target=_blank} : “This is a sweet simple framework that solves some really nice problems… Data validations and settings management using Python type annotations, and it’s the Python type annotations that makes me really extra happy… It works automatically with all the IDE’s you already have.” —Michael Kennedy
Python Pydantic Introduction – Give your data classes super powers{target=_blank} : A talk by Alexander Hultnér originally for the Python Pizza Conference introducing new users to Pydantic and walking through the core features of Pydantic. —>