-
-
Notifications
You must be signed in to change notification settings - Fork 286
/
metadata.py
47 lines (37 loc) · 1.38 KB
/
metadata.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from __future__ import annotations
from collections.abc import Sequence
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import Self
from zarr.core.common import JSON
from dataclasses import dataclass, fields
__all__ = ["Metadata"]
@dataclass(frozen=True)
class Metadata:
def to_dict(self) -> dict[str, JSON]:
"""
Recursively serialize this model to a dictionary.
This method inspects the fields of self and calls `x.to_dict()` for any fields that
are instances of `Metadata`. Sequences of `Metadata` are similarly recursed into, and
the output of that recursion is collected in a list.
"""
out_dict = {}
for field in fields(self):
key = field.name
value = getattr(self, key)
if isinstance(value, Metadata):
out_dict[field.name] = getattr(self, field.name).to_dict()
elif isinstance(value, str):
out_dict[key] = value
elif isinstance(value, Sequence):
out_dict[key] = tuple(v.to_dict() if isinstance(v, Metadata) else v for v in value)
else:
out_dict[key] = value
return out_dict
@classmethod
def from_dict(cls, data: dict[str, JSON]) -> Self:
"""
Create an instance of the model from a dictionary
"""
...
return cls(**data)