-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c4f39f9
commit 7a6387e
Showing
4 changed files
with
77 additions
and
44 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
import copy | ||
import typing as t | ||
from pydantic import BaseModel, create_model | ||
|
||
ModelClass = t.TypeVar("ModelClass", bound=BaseModel) | ||
|
||
|
||
def all_optional_model(model: t.Type[ModelClass]) -> t.Type[ModelClass]: | ||
""" | ||
This decorator can be used to make all fields of a pydantic model optionals. | ||
Args: | ||
model: The pydantic model to modify. | ||
Returns: | ||
The modified model. | ||
""" | ||
kwargs = {} | ||
for field_name, field_info in model.model_fields.items(): | ||
new = copy.deepcopy(field_info) | ||
new.default = None | ||
new.annotation = t.Optional[field_info.annotation] # type: ignore | ||
kwargs[field_name] = (new.annotation, new) | ||
|
||
return create_model(f"Partial{model.__name__}", __base__=model, __module__=model.__module__, **kwargs) # type: ignore |