-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Closed
Labels
Description
For use in PATCH methods and such.
Something along the lines of:
from typing import Annotated, Any, TypeVar
from typing import Annotated, Any
from pydantic import BaseModel, WrapValidator, WrapSerializer, WithJsonSchema
from pydantic_core import PydanticOmit
from pydantic_core.core_schema import SerializerFunctionWrapHandler, ValidatorFunctionWrapHandler
def _ser_missing(v: Any, handler: SerializerFunctionWrapHandler) -> Any:
if v is Missing:
raise PydanticOmit
return handler(v)
def _val_missing(v: Any, handler: ValidatorFunctionWrapHandler) -> Any:
if v is Missing:
return v
return handler(v)
T = TypeVar('T')
MaybeMissing = Annotated[T, WrapValidator(_val_missing), WrapSerializer(_ser_missing), WithJsonSchema({'type': []})]
Missing: MaybeMissing[Any] = object() # type: ignore
class Model(BaseModel):
y: int
x: MaybeMissing[int] = Missing
print(Model.model_json_schema())
print(Model(y=1).model_dump())
print(Model(y=1, x=2).model_dump())
The main thing missing for this is support for PydanticOmit
in serializer.
Needs some thinking around if it should be a type alias for None or a new type and other details.
Selected Assignee: @dmontagu
pydantic-hooky, jcrist, hampuskraft, awoimbee and ricosaurus