Skip to content

Commit f7640f6

Browse files
authored
fix: implement pydantic model deserialization (#1877)
Closes #1876
1 parent a008de7 commit f7640f6

File tree

2 files changed

+6
-11
lines changed

2 files changed

+6
-11
lines changed
Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
from __future__ import annotations
22

3-
from typing import TYPE_CHECKING, Any, Optional
3+
from typing import Any, Optional
44

55
from marshmallow import fields
6-
7-
if TYPE_CHECKING:
8-
from pydantic import BaseModel
6+
from pydantic import BaseModel, RootModel
97

108

119
class PydanticModel(fields.Field):
@@ -14,8 +12,5 @@ def _serialize(self, value: Optional[BaseModel], attr: Any, obj: Any, **kwargs)
1412
return None
1513
return value.model_dump()
1614

17-
def _deserialize(self, value: dict, attr: Any, data: Any, **kwargs) -> dict:
18-
# Not implemented as it is non-trivial to deserialize json back into a model
19-
# since we need to know the model class to instantiate it.
20-
# Would rather not implement right now rather than implement incorrectly.
21-
raise NotImplementedError("Model fields cannot be deserialized directly.")
15+
def _deserialize(self, value: dict, attr: Any, data: Any, **kwargs) -> BaseModel:
16+
return RootModel(value)

tests/unit/artifacts/test_model_artifact.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,5 +21,5 @@ def test_to_dict(self, model_artifact: ModelArtifact):
2121

2222
def test_deserialization(self, model_artifact):
2323
artifact_dict = model_artifact.to_dict()
24-
with pytest.raises(NotImplementedError):
25-
BaseArtifact.from_dict(artifact_dict)
24+
model = BaseArtifact.from_dict(artifact_dict)
25+
assert isinstance(model, ModelArtifact)

0 commit comments

Comments
 (0)