Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Serialize data classes based on their fields only #2697

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions ax/storage/json_store/encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ def object_to_json( # noqa C901
},
}
elif dataclasses.is_dataclass(obj):
field_names = [f.name for f in dataclasses.fields(obj)]
return {
"__type": _type.__name__,
**{
Expand All @@ -144,6 +145,7 @@ def object_to_json( # noqa C901
class_encoder_registry=class_encoder_registry,
)
for k, v in obj.__dict__.items()
if k in field_names
},
}

Expand Down
19 changes: 19 additions & 0 deletions ax/storage/json_store/tests/test_json_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,25 @@ def test_EncodeDecode(self) -> None:
else:
raise e

def test_EncodeDecode_dataclass_with_initvar(self) -> None:
@dataclasses.dataclass
class TestDataclass:
a_field: int
not_a_field: dataclasses.InitVar[int | None] = None

def __post_init__(self, doesnt_serialize: None) -> None:
self.not_a_field = 1

obj = TestDataclass(a_field=-1)
as_json = object_to_json(obj=obj)
self.assertEqual(as_json, {"__type": "TestDataclass", "a_field": -1})
recovered = object_from_json(
object_json=as_json, decoder_registry={"TestDataclass": TestDataclass}
)
self.assertEqual(recovered.a_field, -1)
self.assertEqual(recovered.not_a_field, 1)
self.assertEqual(obj, recovered)

def test_EncodeDecodeTorchTensor(self) -> None:
x = torch.tensor(
[[1.0, 2.0], [3.0, 4.0]], dtype=torch.float64, device=torch.device("cpu")
Expand Down
Loading