-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserdepy.py
95 lines (73 loc) · 3.1 KB
/
serdepy.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
from typing import T, Type
from dataclasses import fields, is_dataclass
import json
class Serializer(json.JSONEncoder):
"""
Serialize objects into a dictionary.
"""
def default(self, obj: object):
if hasattr(obj, 'to_dict'):
return obj.to_dict()
return super().default(obj)
class Deserializer(json.JSONDecoder):
"""
Deserialize dictionary objects back to an object.
"""
def __init__(self, *args, **kwargs):
super().__init__(object_hook=self.from_dict, *args, **kwargs)
def from_dict(self, dictionary: dict) -> object:
for key, value in dictionary.items():
if isinstance(value, dict):
dictionary[key] = self.from_dict(value)
elif isinstance(value, list):
for i, e in enumerate(value):
if isinstance(e, dict):
value[i] = self.from_dict(e)
return dictionary
def serde(cls: Type[T]) -> Type[T]:
"""
Decorator to add serialization/deserialization methods to a class.
"""
setattr(cls, 'to_dict', to_dict)
setattr(cls, 'from_dict', classmethod(from_dict))
setattr(cls, 'serialize', serialize)
setattr(cls, 'deserialize', classmethod(deserialize))
return cls
def to_dict(obj: object) -> dict:
"""
Return a dictionary representation of the object.
"""
if hasattr(obj, '__annotations__'):
return {f: getattr(obj, f) for f in obj.__annotations__}
return {}
def from_dict(cls: Type[T], dictionary: dict) -> T:
"""
Return an instance of the class from a dictionary while also performing type validation.
"""
obj: T = cls.__new__(cls)
for field_name, field_type in obj.__annotations__.items():
if field_name in dictionary:
value = dictionary[field_name] # The actual value from the dictionary
if isinstance(value, list) or isinstance(field_type, _GenericAlias):
inner_type = field_type.__args__[0]
# Recursively call from_dict for each element in the list
value = [inner_type.from_dict(v) if isinstance(v, dict) else v for v in value]
elif isinstance(value, dict):
# Recursively call from_dict for nested structures
value = field_type.from_dict(value)
# Set the value for each of the fields from the dictionary
setattr(obj, field_name, value)
return obj
def serialize(obj: object, indent: int = 2) -> str:
"""
Return a JSON representation of the object using the Serializer.
"""
return json.dumps(obj.to_dict(), cls=Serializer, indent=indent)
def deserialize(cls: Type[T], data: str) -> T:
"""
Return an instance of the class from a JSON string, ensuring it represents a JSON object.
"""
dictionary: dict = json.loads(data)
if not isinstance(dictionary, dict):
raise TypeError(f"{cls.__name__}.deserialize(): expected a JSON object, but got {type(dictionary).__name__}")
return from_dict(cls, dictionary)