Skip to content

Instantly share code, notes, and snippets.

@AboTyim
Last active September 7, 2024 09:45
Show Gist options
  • Save AboTyim/26fd6463226e79461b7e27faf00bc2f5 to your computer and use it in GitHub Desktop.
Save AboTyim/26fd6463226e79461b7e27faf00bc2f5 to your computer and use it in GitHub Desktop.
Make every field as optional with Pydantic v2
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