Skip to content

Commit

Permalink
fix: fix serialization of events (#110)
Browse files Browse the repository at this point in the history
  • Loading branch information
tlambert03 authored Jul 28, 2023
1 parent afe033d commit d73a660
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/useq/_base_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
IO,
TYPE_CHECKING,
Any,
ClassVar,
Dict,
Optional,
Sequence,
Expand All @@ -15,10 +16,13 @@
Union,
)

import numpy as np
from pydantic import BaseModel, root_validator
from pydantic.error_wrappers import ErrorWrapper, ValidationError
from pydantic.utils import ROOT_KEY

from useq._utils import ReadOnlyDict

if TYPE_CHECKING:
from pydantic.types import StrBytes

Expand All @@ -36,6 +40,7 @@ class Config:
allow_population_by_field_name = True
extra = "allow"
frozen = True
json_encoders: ClassVar[dict] = {"ReadOnlyDict": dict}

@root_validator(pre=False, skip_on_failure=True)
def _validate_kwargs(cls, values: Dict[str, Any]) -> Dict[str, Any]:
Expand Down Expand Up @@ -197,6 +202,12 @@ def yaml(
yaml.SafeDumper.add_multi_representer(
Enum, lambda dumper, data: dumper.represent_str(str(data.value))
)
yaml.SafeDumper.add_multi_representer(
ReadOnlyDict, lambda dumper, data: dumper.represent_dict(data)
)
yaml.SafeDumper.add_multi_representer(
np.floating, lambda dumper, data: dumper.represent_float(float(data))
)

data = self.dict(
include=include,
Expand Down
4 changes: 4 additions & 0 deletions tests/test_serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,7 @@ def test_serialization(mda1: MDASequence, ext: str) -> None:
assert json.loads(mda.json(exclude={"uid"})) == json.loads(text)
else:
assert mda.yaml() == text

it = iter(mda)
for _ in range(20):
assert getattr(next(it), ext)()

0 comments on commit d73a660

Please sign in to comment.