-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Custom serialization and validation for numpy arrays
- Loading branch information
Showing
6 changed files
with
42 additions
and
16 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
Empty file.
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 @@ | ||
""" | ||
Custom pydantic type to allow for serialization and validation of ndarray | ||
""" | ||
import numpy as np | ||
from pydantic import BeforeValidator, PlainSerializer | ||
from typing_extensions import Annotated | ||
|
||
|
||
def nd_array_custom_before_validator(x): | ||
# custom before validation logic | ||
if isinstance(x, list): | ||
return np.asarray(x) | ||
return x | ||
|
||
|
||
def nd_array_custom_serializer(x): | ||
# custom serialization logic | ||
return str(x) | ||
|
||
|
||
PydanticNDArray = Annotated[ | ||
np.ndarray, | ||
BeforeValidator(nd_array_custom_before_validator), | ||
PlainSerializer(nd_array_custom_serializer, return_type=str), | ||
] |