Pydantic v2 vs dataclass
Python gives you two practical ways to turn a JSON document into typed objects: Pydantic v2 (BaseModel) and the standard library's @dataclass. Both express the same fields, but they behave very differently the moment a real payload deviates from your sample.
| Requirement | Pydantic v2 | @dataclass |
|---|---|---|
| Wire key aliases (orderId → order_id) | Field(alias="orderId") + populate_by_name=True | Not built in; needs manual rename or # JSON comment |
| Runtime type validation | Validates and coerces on model_validate() | None — types are hints only at runtime |
| Third-party dependencies | Requires pydantic>=2 | Zero — standard library only |
| Default field placement | Allowed in any order | Fields with = None must come after required fields |
If the document crosses an HTTP or queue boundary, Pydantic pays for itself on the first mismatched field. If you only need lightweight containers inside a script with no dependencies, a dataclass avoids adding a package.
Keywords and camelCase keys
JSON objects routinely use keys that are either camelCase (orderId) or reserved Python keywords (class, from, import). Writing class: str in a class body is a SyntaxError, and renaming a field to order_id without an alias makes the loader drop the incoming value silently.
# Input JSON
{"orderId": 42, "class": "express", "from": "warehouse-a"}
# Pydantic v2 output
class Order(BaseModel):
model_config = ConfigDict(populate_by_name=True)
order_id: int = Field(alias="orderId")
class_: str = Field(alias="class")
from_: str = Field(alias="from")Appending a trailing underscore follows PEP 8, and pairing it with Field(alias=...) keeps deserialisation bound to the exact JSON wire key. Notice also that nested child classes must be declared above the parent model in Python when from __future__ import annotations is not used, because Pydantic evaluates annotations as the class body runs.
Optional vs nullable: two different facts
Single-sample generators conflate two situations that mean completely different things in a schema:
- Always present, sometimes null. Every object has the key, and one record sets it to
null. The type isOptional[str]with no default, so a missing key still fails validation. - Sometimes absent from the payload. Some array elements omit the key altogether. That becomes
Optional[str] = None, allowing both absence andnull.
To tell the two apart, paste an array of several real responses into the JSON to Python generator instead of a single object.
Dataclass field ordering and 64-bit ints
In a @dataclass, declaring an optional field with = None before a required field raises TypeError: non-default argument follows default argument as soon as the module is imported. Required fields must therefore be sorted ahead of optional ones:
@dataclass
class Order:
order_id: int
class_: str
note: Optional[str] = None # moved after required fieldsFinally, remember that Python's int is arbitrary precision, whereas JavaScript's JSON.parse uses IEEE-754 doubles. If your JSON sends 19-digit IDs as bare numbers, see why JSON numbers lose precision above 2^53 before generating models in the browser.