Pydantic or a dataclass? Python types from JSON
A dataclass with type hints checks nothing at all. Pydantic checks everything. Here is when each one is the right answer.
Generate Python from a JSON sample and you get a @dataclass with a reader
written out by hand. Turn on Pydantic BaseModel and you get this instead:
from pydantic import BaseModel
from datetime import datetime
class Root(BaseModel):
id: int
name: str
joined: datetime
Shorter, and it does more. But not always what you want.
Python type hints check nothing
This is the fact everything else follows from:
from dataclasses import dataclass
@dataclass
class User:
id: int
name: str
User(id="not a number", name=42) # works fine
A type hint is documentation that mypy reads. At run time Python ignores
it. So a plain dataclass built from json.loads output gives you a type that
says int and a value that is a string from the API.
This is why the generated dataclass comes with all those from_dict and
to_dict functions: they are the check, written by hand, because the
language does not provide one.
What Pydantic adds
Root.model_validate_json(text)
One line. It parses, checks every field, converts what it safely can, and
raises ValidationError with the path to the bad field when it cannot.
It also handles the things that are tedious by hand:
- a date string into
datetime; - a nested model, all the way down;
- a default for a missing field;
- an alias, so
user_idin the JSON becomesuser_idoruserIdin Python; Decimalfor money, kept exact.
When to use the plain dataclass
No dependency. A script, a lambda with a size limit, a library that does not want to force Pydantic on its users.
Speed, sometimes. A dataclass is a thin object. Pydantic v2 is fast — its core is in Rust — but a check always costs more than no check.
You trust the data. Reading your own file, written by your own program, in the same deploy.
When to use Pydantic
The data came from outside. An HTTP response, a request body, a queue, a file a user uploaded. Everything in a type is not a check applies to Python exactly as it does to TypeScript.
You already have it. FastAPI is built on Pydantic. If you use FastAPI, your models should be Pydantic models, and the API documentation comes out of them for free.
Two Pydantic details to get right
Strict or not. By default Pydantic converts: the string "42" becomes the
integer 42. That is friendly and sometimes hides a real fault in the data.
model_config = ConfigDict(strict=True) turns it off, and then a string where
an int belongs is an error.
v1 or v2. They are different libraries with the same name. BaseModel
methods were renamed: parse_raw became model_validate_json, .dict()
became .model_dump(). The code this tool writes is v2.
The Python version option matters
Set it to 3.10 or later and the generator uses the modern form:
nickname: str | None = None
Set it lower and you get:
from typing import Optional
nickname: Optional[str] = None
Both are correct. Match what the rest of your project does.
Naming
Python wants snake_case, and most JSON already is, so usually nothing is
renamed. When a key is not a legal Python name — 2fa_enabled, class,
user-id — the generator renames it and keeps the original, either in the
hand-written reader or in a Pydantic alias. Do not edit the new name without
the alias. See field names.
Try it
Paste an API answer, generate Python with Pydantic BaseModel off and then on. The second is a third of the length and checks more. That comparison is the clearest argument for the dependency.
Try it on your own JSON. The generator runs in your browser. Nothing is uploaded, and nothing is stored on a server.
Open JSON to CodeRead next
Go json tags, omitempty, and the zero value trap
Why every generated Go struct has tags, what omitempty really drops, and why a pointer is sometimes the only honest type.
Go json tags, omitempty, and the zero value trap
Why every generated Go struct has tags, what omitempty really drops, and why a pointer is sometimes the only honest type.