Question presented to candidate:
"In Pydantic v2, how would you validate a plain list[int] or a TypedDict that is not a BaseModel? What does strict mode change, and where can you turn it on? And how do you get a derived value like total into model_dump() output?"
What a strong answer should cover:
TypeAdapter(T)builds a pydantic-core validator and serializer for any type (list[int], TypedDict, unions,Annotatedconstraints, dataclasses):validate_python,validate_json,dump_python/dump_json,json_schema; build it once and reuse it because building is the expensive part- Lax mode (default) coerces sensible inputs (
"3"to3,3.0to3) but still refuses lossy ones (2.9for an int); strict mode accepts only the exact type for Python input - Strict at three levels:
ConfigDict(strict=True)on the model,Field(strict=True)/StrictIntper field,strict=Trueper validation call; JSON input is looser even in strict mode (a JSON string can be adate) @computed_fieldon a@property(orcached_property) puts a derived value intomodel_dump,model_dump_jsonand the serialization JSON schema, but not into validation input- Trade-offs: strict mode is for trusted typed producers (internal services); lax for human / HTTP input; computed fields run on every dump unless cached
Clarifying questions expected:
- Is the data coming from JSON (an HTTP body, a queue) or from Python objects in the same process?
- Should a string like
"42"be accepted for an integer field, or is that a bug in the producer we want to catch?
Code / implementation expected: Yes โ a reused TypeAdapter, one strict and one lax validation of the same input, and a model with a @computed_field shown in model_dump().