-
Notifications
You must be signed in to change notification settings - Fork 421
/
Copy pathdataclass.py
45 lines (35 loc) · 1.39 KB
/
dataclass.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
from __future__ import annotations
from dataclasses import asdict, is_dataclass
from typing import Any
from aws_lambda_powertools.utilities.idempotency.exceptions import (
IdempotencyModelTypeError,
IdempotencyNoSerializationModelError,
)
from aws_lambda_powertools.utilities.idempotency.serialization.base import (
BaseIdempotencyModelSerializer,
BaseIdempotencySerializer,
)
DataClass = Any
class DataclassSerializer(BaseIdempotencyModelSerializer):
"""
A serializer class for transforming data between dataclass objects and dictionaries.
"""
def __init__(self, model: type[DataClass]):
"""
Parameters
----------
model: type[DataClass]
A dataclass type to be used for serialization and deserialization
"""
self.__model: type[DataClass] = model
def to_dict(self, data: DataClass) -> dict:
return asdict(data)
def from_dict(self, data: dict) -> DataClass:
return self.__model(**data)
@classmethod
def instantiate(cls, model_type: Any) -> BaseIdempotencySerializer:
if model_type is None:
raise IdempotencyNoSerializationModelError("No serialization model was supplied")
if not is_dataclass(model_type):
raise IdempotencyModelTypeError("Model type is not inherited of dataclass type")
return cls(model=model_type) # type: ignore[arg-type]