Last active
September 7, 2024 09:45
-
-
Save AboTyim/26fd6463226e79461b7e27faf00bc2f5 to your computer and use it in GitHub Desktop.
Make every field as optional with Pydantic v2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from copy import deepcopy | |
from typing import Any, Tuple | |
from pydantic import BaseModel, create_model, Field | |
from pydantic.fields import FieldInfo | |
def fields_optional(model: type[BaseModel]): | |
def make_field_optional( | |
field: FieldInfo, default: Any = None | |
) -> Tuple[Any, FieldInfo]: | |
new = deepcopy(field) | |
new.default = default | |
# field as optional (type: ignore) | |
new.annotation = Optional[field.annotation] | |
return new.annotation, new | |
return create_model( | |
f"{model.__name__}", | |
__base__=model, | |
__module__=model.__module__, | |
**{ | |
field_name: make_field_optional(field_info) | |
for field_name, field_info in model.model_fields.items() | |
}, | |
) | |
class SourceCreateSchema(BaseModel): | |
name: str = Field(min_length=3, max_length=50) | |
info: str = Field(min_length=20) | |
@fields_optional | |
class SourceUpdateSchema(SourceCreateSchema): | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment