Dataclass With Pydantic Validation
Define a dataclass with Pydantic for runtime validation type coercion and JSON serialization.
Code
from pydantic import BaseModel, Field, validator
class User(BaseModel):
email: str
age: int = Field(ge=18, le=120)
tags: list[str] = Field(default_factory=list)
@validator('email')
def validate_email(cls, v):
if '@' not in v:
raise ValueError('invalid email')
return v.lower()Inside the snippet
Dataclass With Pydantic Validation is built around the class User and the function validate_email.
Reach for pydantic and what you get is BaseModel, Field, validator — that is the whole API contact area. When the guard condition holds, ValueError is thrown rather than a bogus value returned.
What to watch for
- External dependency:
pydantic— install it before running the snippet. - The guard
'@' not in vshort-circuits the flow with an earlyraisewhen its condition holds.
Using it
The entry-point signature is def validate_email(cls, v)
Import validate_email from the file and call it — the rest of the code is implementation detail.
Key statements
def validate_email(cls, v):
if '@' not in v:
raise ValueError('invalid email')
return v.lower()
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Is there a failure path for bad input?
- The code throws `ValueError` — the guard `'@' not in v` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
- Does this require external packages?
- Yes — `pydantic`. Add it to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.