turbo_broccoli.custom.dataclass

Dataclass serialization

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

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__.