Dataclasses vs Pydantic
Dataclasses vs Pydantic is a choice about trust: a Python dataclass stores data your own code makes, and Pydantic checks and converts input from outside.
Read Python Dataclasses, Python Dataclass Validation with post_init and Python JSON first. This lesson shows what a dataclass leaves unchecked, what outside data needs with the standard library alone, and the same record as a Pydantic model. After it, you can tell which of the two a piece of data needs. Pydantic is a third-party library, installed with pip install pydantic. Its examples do not run in this browser, so each one shows its output in comments. No graded exercise needs it.
A dataclass does not check types
A type hint documents a field. The generated __init__() stores whatever value it gets.
from dataclasses import dataclass@dataclassclass Result: student: str score: intresult = Result("Ada", "72")print(result)print(result.score + 1) # this line raises TypeErrorThis prints Result(student='Ada', score='72'), then stops with TypeError: can only concatenate str (not "int") to str. The string got in without a word, and the error shows up later, on another line. That is fine for trusted data: values your own code makes, where you write every call.
Check outside data yourself
JSON from a file, a form or a web API is untrusted data. A number can arrive as a string, and a key can be missing. With the standard library, you convert and check each value at the edge of your program, before you make the dataclass.
import jsonfrom dataclasses import dataclass@dataclassclass Result: student: str score: intdef result_from(item): return Result(item["student"], int(item["score"]))text = '[{"student": "Ada", "score": "72"}, {"student": "Bo", "score": "ten"}, {"student": "Di"}]'for item in json.loads(text): try: print(result_from(item)) except (KeyError, ValueError) as error: print("rejected:", type(error).__name__, error)This prints Result(student='Ada', score=72), then rejected: ValueError invalid literal for int() with base 10: 'ten', then rejected: KeyError 'score'. int() turns "72" into 72 and fails on "ten". A missing key raises KeyError, and type(error).__name__ is the name of the error's class. The string text stands in for JSON read from a file or a web request, and result_from() is the edge: the one place where outside data becomes a Result. Every further rule, such as a score range, is more code you write and test yourself.
The same record in Pydantic
A Pydantic model is a class that inherits from BaseModel. It looks like the dataclass, with the same type hints, but here the hints do work: Pydantic converts each value to the hinted type, or rejects it. That is the main difference between the two. Field(ge=0, le=100) adds a range rule: greater than or equal to 0, less than or equal to 100.
import json
from pydantic import BaseModel, Field, ValidationError
class Result(BaseModel):
student: str
score: int = Field(ge=0, le=100)
text = '[{"student": "Ada", "score": "72"}, {"student": "Bo", "score": "ten"}, {"student": "Cy", "score": 110}, {"student": "Di"}]'
for item in json.loads(text):
try:
print(Result.model_validate(item))
except ValidationError as error:
print("rejected:", error.errors()[0]["msg"])
# student='Ada' score=72
# rejected: Input should be a valid integer, unable to parse string as an integer
# rejected: Input should be less than or equal to 100
# rejected: Field required
model_validate() builds a model from a dictionary, and printing a model shows its fields as student='Ada' score=72. Every failure raises one ValidationError. error.errors() is a list with one dictionary per failed field, and its "msg" key holds the message. The range rule and the missing key need no code of your own.
Do not mix up the two kinds of validation. A dataclass rejects only what you check yourself in __post_init__(), and it never converts a value. A Pydantic model checks every type hint and every Field() rule, and converts values too.
Pydantic converts before it checks
By default Pydantic accepts "72" for an int field and stores 72. That helps with form data, where every value arrives as text. It surprises you if you expected a check only. Add strict=True to accept real integers only.
from pydantic import BaseModel, Field, ValidationError
class Result(BaseModel):
student: str
score: int = Field(ge=0, le=100)
class StrictResult(BaseModel):
student: str
score: int = Field(ge=0, le=100, strict=True)
print(Result(student="Ada", score="72").model_dump())
try:
StrictResult(student="Ada", score="72")
except ValidationError as error:
print("rejected:", error.errors()[0]["msg"])
# {'student': 'Ada', 'score': 72}
# rejected: Input should be a valid integer
model_dump() exports a model as a dictionary, as asdict() does for a dataclass.
Choose by where the data comes from
- Use a dataclass for records your own code makes and uses, such as a gradebook built in a loop. It is in the standard library, and
__post_init__()can still guard a rule that every object must keep. - Use Pydantic at the edge, where JSON, form fields or a config file enter your program and a value can be missing or of the wrong type. Web frameworks such as FastAPI use Pydantic models to check each request.
- Many programs use both: Pydantic checks the input once, and the rest of the code works with trusted objects.
Note: A Pydantic model takes keyword arguments only: Result(student="Ada", score=72), not Result("Ada", 72). The hand-written check above lets through some values that Pydantic rejects. A JSON score of 72.5 becomes 72, because int() cuts off the fraction, and a number as student is never noticed. Extra keys are ignored by both. To stay short, the examples read JSON from a fixed string instead of a file or a web request, and print only the first message of each ValidationError.
See also: Data validation, Python Dataclass asdict Examples.
Your turn
Finish result_from() with the standard library only. Raise ValueError("no name") for an empty student, and ValueError("not a whole number") for a score that is a float, such as 72.5. Then convert the score with int() and return a Result.
Result(student='Ada', score=72) rejected: no name rejected: invalid literal for int() with base 10: 'ten' rejected: not a whole number Result(student='Cy', score=81)
import jsonfrom dataclasses import dataclass@dataclassclass Result: student: str score: intdef result_from(item): # add two checks: raise ValueError("no name") for an empty student, # and ValueError("not a whole number") when the score is a float # then convert the score with int() in the line below return Result(item["student"], item["score"])text = '[{"student": "Ada", "score": "72"}, {"student": "", "score": "64"}, {"student": "Bo", "score": "ten"}, {"student": "Di", "score": 72.5}, {"student": "Cy", "score": 81}]'for item in json.loads(text): try: print(result_from(item)) except (KeyError, ValueError) as error: print("rejected:", error)