Python's most widely used data validation library. Powered by Rust core in v2 (5–50x faster than v1). Type-hint-driven models with automatic parsing, validation, and serialization.
user.model_dump()# → dictuser.model_dump(exclude_unset=True)# only explicitly set fieldsuser.model_dump(by_alias=True)# use field aliasesuser.model_dump_json()# → JSON stringuser.model_dump(mode="json")# dict with JSON-safe types
frompydanticimportfield_validator,model_validatorclassOrder(BaseModel):price:floatquantity:int@field_validator("price")@classmethoddefprice_positive(cls,v:float)->float:ifv<=0:raiseValueError("price must be positive")returnv@model_validator(mode="after")defcheck_total(self)->"Order":ifself.price*self.quantity>10_000:raiseValueError("order total exceeds limit")returnself