Complete worked example
python
from pydantic import BaseModel, ValidationError
class ProfilePatch(BaseModel):
nickname: str | None
bio: str | None = None
def inspect_example(payload):
try:
patch = ProfilePatch.model_validate(payload)
return {"values": patch.model_dump(exclude_unset=True),
"set": sorted(patch.model_fields_set)}
except ValidationError as error:
return {"error": sorted({e["type"] for e in error.errors()})}- Reasoning
- Pydantic records the names supplied at validation time in model_fields_set. model_dump(exclude_unset=True) uses that information when building a patch mapping. It includes an explicitly supplied nickname=None but omits bio when no bio was sent. The example returns both the selected values and the sorted field set so the fixture can observe this policy directly. For nickname="Ada", only nickname appears. For nickname=None, that same key remains present with null. With no nickname key, the baseline returns a missing error rather than silently creating a patch.