Skip to content

Commit d73a660

Browse files
authored
fix: fix serialization of events (#110)
1 parent afe033d commit d73a660

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

src/useq/_base_model.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
IO,
77
TYPE_CHECKING,
88
Any,
9+
ClassVar,
910
Dict,
1011
Optional,
1112
Sequence,
@@ -15,10 +16,13 @@
1516
Union,
1617
)
1718

19+
import numpy as np
1820
from pydantic import BaseModel, root_validator
1921
from pydantic.error_wrappers import ErrorWrapper, ValidationError
2022
from pydantic.utils import ROOT_KEY
2123

24+
from useq._utils import ReadOnlyDict
25+
2226
if TYPE_CHECKING:
2327
from pydantic.types import StrBytes
2428

@@ -36,6 +40,7 @@ class Config:
3640
allow_population_by_field_name = True
3741
extra = "allow"
3842
frozen = True
43+
json_encoders: ClassVar[dict] = {"ReadOnlyDict": dict}
3944

4045
@root_validator(pre=False, skip_on_failure=True)
4146
def _validate_kwargs(cls, values: Dict[str, Any]) -> Dict[str, Any]:
@@ -197,6 +202,12 @@ def yaml(
197202
yaml.SafeDumper.add_multi_representer(
198203
Enum, lambda dumper, data: dumper.represent_str(str(data.value))
199204
)
205+
yaml.SafeDumper.add_multi_representer(
206+
ReadOnlyDict, lambda dumper, data: dumper.represent_dict(data)
207+
)
208+
yaml.SafeDumper.add_multi_representer(
209+
np.floating, lambda dumper, data: dumper.represent_float(float(data))
210+
)
200211

201212
data = self.dict(
202213
include=include,

tests/test_serialization.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,7 @@ def test_serialization(mda1: MDASequence, ext: str) -> None:
1616
assert json.loads(mda.json(exclude={"uid"})) == json.loads(text)
1717
else:
1818
assert mda.yaml() == text
19+
20+
it = iter(mda)
21+
for _ in range(20):
22+
assert getattr(next(it), ext)()

0 commit comments

Comments
 (0)