turbo_broccoli.custom.dataclass
Dataclass serialization
1"""Dataclass serialization""" 2 3from typing import Any 4 5from turbo_broccoli.context import Context 6from turbo_broccoli.exceptions import DeserializationError, TypeNotSupported 7 8 9def _json_to_dataclass_v3(dct: dict, ctx: Context) -> Any: 10 class_name = dct["__type__"].split(".")[-1] 11 return ctx.dataclass_types[class_name](**dct["data"]) 12 13 14# pylint: disable=missing-function-docstring 15def from_json(dct: dict, ctx: Context) -> Any: 16 decoders = { 17 3: _json_to_dataclass_v3, 18 } 19 try: 20 return decoders[dct["__version__"]](dct, ctx) 21 except KeyError as exc: 22 raise DeserializationError() from exc 23 24 25def to_json(obj: Any, ctx: Context) -> dict: 26 """ 27 Serializes a dataclass into JSON by cases. The return dict has the 28 following structure 29 30 ```py 31 { 32 "__type__": "dataclass.<CLASS NAME>", 33 "__version__": 3, 34 "class": <str>, 35 "data": {...}, 36 } 37 ``` 38 39 where the `{...}` is `obj.__dict__`. 40 """ 41 if hasattr(obj, "__dataclass_fields__"): 42 return { 43 "__type__": "dataclass." + obj.__class__.__name__, 44 "__version__": 3, 45 "data": obj.__dict__, 46 } 47 raise TypeNotSupported()
26def to_json(obj: Any, ctx: Context) -> dict: 27 """ 28 Serializes a dataclass into JSON by cases. The return dict has the 29 following structure 30 31 ```py 32 { 33 "__type__": "dataclass.<CLASS NAME>", 34 "__version__": 3, 35 "class": <str>, 36 "data": {...}, 37 } 38 ``` 39 40 where the `{...}` is `obj.__dict__`. 41 """ 42 if hasattr(obj, "__dataclass_fields__"): 43 return { 44 "__type__": "dataclass." + obj.__class__.__name__, 45 "__version__": 3, 46 "data": obj.__dict__, 47 } 48 raise TypeNotSupported()
Serializes a dataclass into JSON by cases. The return dict has the following structure
{
"__type__": "dataclass.<CLASS NAME>",
"__version__": 3,
"class": <str>,
"data": {...},
}
where the {...}
is obj.__dict__
.