pycraftbox-serialization 4.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pycraftbox/serialization/__init__.py +23 -0
- pycraftbox/serialization/base_dataclass.py +303 -0
- pycraftbox/serialization/serializer.py +366 -0
- pycraftbox_serialization-4.0.0.dist-info/METADATA +10 -0
- pycraftbox_serialization-4.0.0.dist-info/RECORD +6 -0
- pycraftbox_serialization-4.0.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Object and dataclass serialization utilities."""
|
|
2
|
+
|
|
3
|
+
from .base_dataclass import BaseDataClass, JsonField, build_json_key_order
|
|
4
|
+
from .serializer import (
|
|
5
|
+
SerializableField,
|
|
6
|
+
is_dict,
|
|
7
|
+
is_primitive,
|
|
8
|
+
is_sequence,
|
|
9
|
+
serialize,
|
|
10
|
+
serialize_leaf,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"BaseDataClass",
|
|
15
|
+
"JsonField",
|
|
16
|
+
"SerializableField",
|
|
17
|
+
"build_json_key_order",
|
|
18
|
+
"is_dict",
|
|
19
|
+
"is_primitive",
|
|
20
|
+
"is_sequence",
|
|
21
|
+
"serialize",
|
|
22
|
+
"serialize_leaf",
|
|
23
|
+
]
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import dataclasses
|
|
4
|
+
import inspect
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
from collections import OrderedDict
|
|
8
|
+
from collections.abc import Mapping, MutableMapping, Sequence
|
|
9
|
+
from datetime import date, datetime, timedelta, tzinfo
|
|
10
|
+
from enum import Enum, auto
|
|
11
|
+
from typing import (
|
|
12
|
+
Annotated,
|
|
13
|
+
Any,
|
|
14
|
+
Callable,
|
|
15
|
+
Optional,
|
|
16
|
+
Protocol,
|
|
17
|
+
Union,
|
|
18
|
+
get_args,
|
|
19
|
+
get_origin,
|
|
20
|
+
get_type_hints,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
import numpy as np
|
|
24
|
+
|
|
25
|
+
from pycraftbox.core import Utils
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class JsonField:
|
|
29
|
+
"""Metadata class to mark attributes for json serialization with an optional order.
|
|
30
|
+
Used in conjunction with the helper function build_json_key_order()."""
|
|
31
|
+
|
|
32
|
+
order: int | None = None
|
|
33
|
+
|
|
34
|
+
def __init__(self, order: Optional[int] = None) -> None:
|
|
35
|
+
self.order = order
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def build_json_key_order(cls: type) -> list[str]:
|
|
39
|
+
"""
|
|
40
|
+
Helper function to build the __json_key_order__ list for a BaseDataClass subclass.
|
|
41
|
+
It scans the class and select attributes whose type is declared as Annotated with JsonField metadata (see usage below).
|
|
42
|
+
It returns the list of attribute names sorted by the order defined in JsonField.order or by
|
|
43
|
+
declaration order if order is None.
|
|
44
|
+
Usage example:
|
|
45
|
+
```python
|
|
46
|
+
from typing import Annotated
|
|
47
|
+
class MyDataClass(BaseDataClass):
|
|
48
|
+
attr1: Annotated[int, JsonField(order=1)]
|
|
49
|
+
attr2: Annotated[str, JsonField()] # no order, will be after attr1
|
|
50
|
+
attr3: float # not marked, will be ignored
|
|
51
|
+
attr4: Annotated[bool, JsonField(order=0)] # will be first
|
|
52
|
+
MyDataClass.__json_key_order__ = build_json_key_order(MyDataClass)
|
|
53
|
+
```
|
|
54
|
+
- résout les annotations même si `from __future__ import annotations` est actif
|
|
55
|
+
- conserve les métadonnées `Annotated[...]` grâce à `include_extras=True`
|
|
56
|
+
- retourne la liste des noms d'attributs marqués avec `JsonField`
|
|
57
|
+
- respecte l'ordre de déclaration, sauf si `order` est défini (tri)
|
|
58
|
+
"""
|
|
59
|
+
# Important: include_extras=True pour conserver Annotated[..., meta]
|
|
60
|
+
hints: dict[str, Any] = get_type_hints(cls, include_extras=True)
|
|
61
|
+
|
|
62
|
+
selected: list[tuple[int, int, str]] = []
|
|
63
|
+
decl_index = 0
|
|
64
|
+
|
|
65
|
+
for name, ann in hints.items():
|
|
66
|
+
if get_origin(ann) is Annotated:
|
|
67
|
+
_base_type, *meta = get_args(ann)
|
|
68
|
+
tag = next((m for m in meta if isinstance(m, JsonField)), None)
|
|
69
|
+
if tag is not None:
|
|
70
|
+
# - ordre explicite si fourni
|
|
71
|
+
# - sinon on garde l'ordre de déclaration via decl_index
|
|
72
|
+
sort_order = tag.order if tag.order is not None else 10**9
|
|
73
|
+
selected.append((sort_order, decl_index, name))
|
|
74
|
+
decl_index += 1
|
|
75
|
+
|
|
76
|
+
selected.sort()
|
|
77
|
+
return [name for _ord, _i, name in selected]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class BaseDataClass:
|
|
81
|
+
_logger = logging.getLogger(__name__)
|
|
82
|
+
|
|
83
|
+
class Recurser:
|
|
84
|
+
_logger = logging.getLogger(__name__)
|
|
85
|
+
anti_loop_list: list[object]
|
|
86
|
+
|
|
87
|
+
def __init__(self) -> None:
|
|
88
|
+
self.anti_loop_list = []
|
|
89
|
+
|
|
90
|
+
def __call__(
|
|
91
|
+
self, obj: Any, *, not_use_key_order: bool = False
|
|
92
|
+
) -> dict[str, Any]:
|
|
93
|
+
pars: dict = {}
|
|
94
|
+
get_attr_json_method = getattr(obj, "__json_attr__", None)
|
|
95
|
+
if get_attr_json_method is not None and callable(get_attr_json_method):
|
|
96
|
+
pars["get_attr_json_method"] = get_attr_json_method
|
|
97
|
+
key_order = getattr(obj, "__json_key_order__", None)
|
|
98
|
+
if not not_use_key_order and key_order is not None:
|
|
99
|
+
try:
|
|
100
|
+
__ = iter(key_order)
|
|
101
|
+
pars["key_order"] = key_order
|
|
102
|
+
except TypeError:
|
|
103
|
+
# not iterable
|
|
104
|
+
pass
|
|
105
|
+
return self.__json_recursion__(obj, **pars) # type: ignore
|
|
106
|
+
|
|
107
|
+
def _make_id(self, obj: Any) -> str:
|
|
108
|
+
obj_class = type(obj)
|
|
109
|
+
return f"{obj_class.__module__}.{obj_class.__name__}_{id(obj)}"
|
|
110
|
+
|
|
111
|
+
def __json_recursion__(
|
|
112
|
+
self,
|
|
113
|
+
obj: Any,
|
|
114
|
+
*,
|
|
115
|
+
get_attr_json_method: Callable[..., Any] | None = None,
|
|
116
|
+
key_order: Sequence[str] | None = None,
|
|
117
|
+
) -> dict[str, Any] | str:
|
|
118
|
+
"""Make the recursives call for the __json__() method"""
|
|
119
|
+
|
|
120
|
+
if Utils.is_primitive(obj):
|
|
121
|
+
return str(obj)
|
|
122
|
+
|
|
123
|
+
obj_id_str = self._make_id(obj)
|
|
124
|
+
|
|
125
|
+
if obj_id_str in self.anti_loop_list:
|
|
126
|
+
print(f"Recursion on {obj_id_str}")
|
|
127
|
+
rep: str
|
|
128
|
+
if "__repr__" in obj.__class__.__dict__:
|
|
129
|
+
rep = obj.__repr__()
|
|
130
|
+
else:
|
|
131
|
+
rep = obj_id_str
|
|
132
|
+
return f"REC:{rep}"
|
|
133
|
+
|
|
134
|
+
res: dict[str, Any] = {}
|
|
135
|
+
self.anti_loop_list.append(obj_id_str)
|
|
136
|
+
|
|
137
|
+
for name, value in inspect.getmembers(obj):
|
|
138
|
+
if inspect.isclass(value):
|
|
139
|
+
continue
|
|
140
|
+
# with key order we can print attribute that starts with _
|
|
141
|
+
if name.startswith("_") and (key_order is None or name not in key_order):
|
|
142
|
+
continue
|
|
143
|
+
# TODO: better to test only things that we accept ?
|
|
144
|
+
if (
|
|
145
|
+
inspect.ismethod(value)
|
|
146
|
+
or inspect.isbuiltin(value)
|
|
147
|
+
or inspect.ismethodwrapper(value)
|
|
148
|
+
or inspect.isroutine(value)
|
|
149
|
+
):
|
|
150
|
+
continue
|
|
151
|
+
if key_order is not None and name not in key_order:
|
|
152
|
+
continue
|
|
153
|
+
self._logger.debug(
|
|
154
|
+
f"Processing attribute {name} with value type {type(value)}"
|
|
155
|
+
)
|
|
156
|
+
res_value: Any = None
|
|
157
|
+
if Utils.is_primitive(value):
|
|
158
|
+
res_value = value
|
|
159
|
+
elif res_value is None and get_attr_json_method is not None:
|
|
160
|
+
res_value = get_attr_json_method(name, value, self)
|
|
161
|
+
elif res_value is None and isinstance(value, Enum):
|
|
162
|
+
res_value = value.value
|
|
163
|
+
elif res_value is None and isinstance(value, datetime):
|
|
164
|
+
res_value = datetime.isoformat(value)
|
|
165
|
+
elif res_value is None and isinstance(value, date):
|
|
166
|
+
res_value = date.isoformat(value)
|
|
167
|
+
elif res_value is None and isinstance(value, np.bool_):
|
|
168
|
+
res_value = bool(value)
|
|
169
|
+
elif res_value is None and Utils.is_sequence(value):
|
|
170
|
+
res_value = []
|
|
171
|
+
for elem in value:
|
|
172
|
+
res_value.append(self(elem))
|
|
173
|
+
elif res_value is None and Utils.is_dict(value):
|
|
174
|
+
res_value = {}
|
|
175
|
+
for k, v in value.items():
|
|
176
|
+
res_value[self(k)] = self(v)
|
|
177
|
+
elif res_value is None:
|
|
178
|
+
json_method = getattr(value, "__json__", None)
|
|
179
|
+
if json_method is not None and callable(json_method):
|
|
180
|
+
res_value = self(value)
|
|
181
|
+
else:
|
|
182
|
+
res_value = str(value)
|
|
183
|
+
|
|
184
|
+
res[name] = res_value
|
|
185
|
+
|
|
186
|
+
self.anti_loop_list.pop()
|
|
187
|
+
if key_order is not None:
|
|
188
|
+
res = OrderedDict(
|
|
189
|
+
sorted(
|
|
190
|
+
[item for item in res.items() if item[0] in key_order],
|
|
191
|
+
key=lambda item: key_order.index(item[0]),
|
|
192
|
+
)
|
|
193
|
+
)
|
|
194
|
+
return res
|
|
195
|
+
|
|
196
|
+
def to_dict(self, recursive: bool = True) -> dict[str, Any]:
|
|
197
|
+
return self.__json__()
|
|
198
|
+
|
|
199
|
+
def __str__(self) -> str:
|
|
200
|
+
json_value = self.__json__()
|
|
201
|
+
try:
|
|
202
|
+
json_str = json.dumps(json_value, indent=2, sort_keys=True, default=str)
|
|
203
|
+
except BaseException as e:
|
|
204
|
+
self._logger.warning(f"Json error on {json_value}")
|
|
205
|
+
raise e
|
|
206
|
+
return f"{json_str}"
|
|
207
|
+
|
|
208
|
+
def __json__(self, *, not_use_key_order: bool = False) -> dict[str, Any]:
|
|
209
|
+
"""Transfrom the object into its json python representation.
|
|
210
|
+
|
|
211
|
+
Parse all attribute of the object and:
|
|
212
|
+
- Skip methods
|
|
213
|
+
- Skip attribute whose name starts with an undercore (_) unless they are in the
|
|
214
|
+
__json_key_order__ list (see below explanation on __json_key_order__)
|
|
215
|
+
- If the attribute has a __json__() method call it
|
|
216
|
+
- call __json_attr__() if the object has such method, pass the
|
|
217
|
+
name and the value of the attribute and expect a string that will be used as
|
|
218
|
+
the string representation of the attribute or None.
|
|
219
|
+
- If a recursive call is detected on an attribute (same object whose __json__() is call twice
|
|
220
|
+
in the same stack frame) then call _json_attr__() for that attribute if it exists
|
|
221
|
+
- For all other cases or when __json_attr__() return None:
|
|
222
|
+
- Stringify attribute that are instance of :Enunm, datetime, date or np.bool
|
|
223
|
+
- otherwise call str() on the value of attribute if it is not an instance of this class
|
|
224
|
+
to void infinite loops.
|
|
225
|
+
- when __json_attr__() returns None on an attribute that is an instance of this class uses the
|
|
226
|
+
name of the class of the attribute followed by the object id of the attribute as it json
|
|
227
|
+
representation.
|
|
228
|
+
|
|
229
|
+
Note about __json_attr__():
|
|
230
|
+
- calling __json_attr__() if supported by the object is the first thing done. You can override any
|
|
231
|
+
behavior like this, just return None if there is nothing special to do with the attribute it will
|
|
232
|
+
be stringigy if any other stringificatoin works for it.
|
|
233
|
+
- It receives three parameter:
|
|
234
|
+
- name : the name of the attribute
|
|
235
|
+
- value: the value of the attribute
|
|
236
|
+
- recurser: __json_attr__() don't call directly __json__() on an object that support this call,
|
|
237
|
+
instead call the recurser with the object as parameter. Furthermore the recurser can be used on
|
|
238
|
+
any object you want to jasonify.
|
|
239
|
+
|
|
240
|
+
If not_use_key_order is False and the object has an attribute named __json_key_order__ that should contain
|
|
241
|
+
a list of the names of the attributes that need to be put in the json representation (attribute missing
|
|
242
|
+
will be skiped) in the order they will be set in the json dictionary.
|
|
243
|
+
"""
|
|
244
|
+
|
|
245
|
+
recurser = self.Recurser()
|
|
246
|
+
return recurser(self)
|
|
247
|
+
|
|
248
|
+
def _add_attributes(self, attrs: Mapping[str, Any]) -> None:
|
|
249
|
+
for att_name, att_value in attrs.items():
|
|
250
|
+
setattr(self, att_name, att_value)
|
|
251
|
+
|
|
252
|
+
@classmethod
|
|
253
|
+
def get_dataclasse_attributes(cls, excludes: Sequence[str] = []) -> list[str]:
|
|
254
|
+
if dataclasses.is_dataclass(cls):
|
|
255
|
+
return [dc.name for dc in dataclasses.fields(cls) if dc.name not in excludes]
|
|
256
|
+
else:
|
|
257
|
+
raise Exception("not a dataclass")
|
|
258
|
+
|
|
259
|
+
@classmethod
|
|
260
|
+
def get_dataclasse_dtypes(
|
|
261
|
+
cls, includes: Sequence[str] = [], time_zone_name: Optional[tzinfo] = None
|
|
262
|
+
) -> Mapping[str, str]:
|
|
263
|
+
res: Mapping[str, Any] = {}
|
|
264
|
+
only_includes = len(includes) > 0
|
|
265
|
+
if dataclasses.is_dataclass(cls):
|
|
266
|
+
for ff in dataclasses.fields(cls):
|
|
267
|
+
if not only_includes or ff.name in includes:
|
|
268
|
+
if ff.type == "int":
|
|
269
|
+
res[ff.name] = "Int64"
|
|
270
|
+
elif ff.type in ["float", "complex"]:
|
|
271
|
+
res[ff.name] = "Float64"
|
|
272
|
+
elif ff.type == "str":
|
|
273
|
+
res[ff.name] = "string"
|
|
274
|
+
elif ff.type in ["bytes", "bytearray"]:
|
|
275
|
+
res[ff.name] = "object"
|
|
276
|
+
elif ff.type == "bool":
|
|
277
|
+
res[ff.name] = "boolean"
|
|
278
|
+
elif ff.type == "datetime":
|
|
279
|
+
if time_zone_name is None:
|
|
280
|
+
res[ff.name] = "datetime64[ns]"
|
|
281
|
+
else:
|
|
282
|
+
res[ff.name] = "datetime64[ns]"
|
|
283
|
+
else:
|
|
284
|
+
res[ff.name] = "object"
|
|
285
|
+
return res
|
|
286
|
+
else:
|
|
287
|
+
raise Exception("not a dataclass")
|
|
288
|
+
|
|
289
|
+
@classmethod
|
|
290
|
+
def from_dict(
|
|
291
|
+
cls,
|
|
292
|
+
*,
|
|
293
|
+
attributes: Mapping[str, Any],
|
|
294
|
+
from_scratch: bool = False,
|
|
295
|
+
**kwargs: Any,
|
|
296
|
+
) -> Any:
|
|
297
|
+
merge_att = kwargs | dict(attributes)
|
|
298
|
+
res = super().__new__(cls)
|
|
299
|
+
if not from_scratch:
|
|
300
|
+
res.__init__(**merge_att) # type: ignore
|
|
301
|
+
else:
|
|
302
|
+
res._add_attributes(merge_att)
|
|
303
|
+
return res
|
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import inspect
|
|
4
|
+
import logging
|
|
5
|
+
from collections import OrderedDict
|
|
6
|
+
from collections.abc import Iterator, Mapping, MutableMapping, Sequence
|
|
7
|
+
from datetime import date, datetime
|
|
8
|
+
from enum import Enum
|
|
9
|
+
from typing import (
|
|
10
|
+
Annotated,
|
|
11
|
+
Any,
|
|
12
|
+
Callable,
|
|
13
|
+
Optional,
|
|
14
|
+
Protocol,
|
|
15
|
+
Union,
|
|
16
|
+
cast,
|
|
17
|
+
get_args,
|
|
18
|
+
get_origin,
|
|
19
|
+
get_type_hints,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
import numpy as np
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class SerializableField:
|
|
26
|
+
"""Metadata class to mark attributes for serialization with an optional order."""
|
|
27
|
+
|
|
28
|
+
order: int | None = None
|
|
29
|
+
|
|
30
|
+
def __init__(self, order: Optional[int] = None) -> None:
|
|
31
|
+
self.order = order
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def serialize(
|
|
35
|
+
obj: Any,
|
|
36
|
+
*,
|
|
37
|
+
serialization_key_order: Sequence[str] | None = None,
|
|
38
|
+
not_use_key_order: bool = False,
|
|
39
|
+
attribute_serializer: Callable[[str, Any, Callable[[Any], Any]], Any] | None = None,
|
|
40
|
+
) -> Any:
|
|
41
|
+
"""Performs serialization of objects.
|
|
42
|
+
Return a dict representing the object with attibute names as keys and its attribute values as found if it is a primitive type otherwise
|
|
43
|
+
as a string representation of its value.
|
|
44
|
+
|
|
45
|
+
Parse all attribute of the object and:
|
|
46
|
+
- Skip methods
|
|
47
|
+
- Skip attribute whose name starts with an undercore (_) unless they are in the
|
|
48
|
+
__serialization_key_order__ list (see below explanation on __serialization_key_order__)
|
|
49
|
+
- If the object has a __serialization_key_order__ attribute and not_use_key_order is False or a serializition_key_order
|
|
50
|
+
parameter is passed, then serilalize only the attributes in the order defined in that list.
|
|
51
|
+
- If at least one of the attributes of the object has the type annotation SerializableField then only those attributes will be serialized
|
|
52
|
+
in the order defined by the order attribute of SerializableField (see SerializableField docstring for details).
|
|
53
|
+
- If the object has a __serialize__() method call it to get the serialization of the object
|
|
54
|
+
- For each attribute of the object:
|
|
55
|
+
- if the object has an __attribute_serializer__() method then call it for each attribute.
|
|
56
|
+
- If a recursive call is detected on an attribute (same object serialization called twice
|
|
57
|
+
in the same stack frame) exists and return a python representation of the object by calling its
|
|
58
|
+
__repr__() methode to avoid infinite loops.
|
|
59
|
+
- For all other cases:
|
|
60
|
+
- If the attribute is a primitive type (int, float, str, bool, None, np.integer, np.floating) use it as is.
|
|
61
|
+
- If the attribute is a iterable like object serialize each element of the iterable recursively.
|
|
62
|
+
- If the attribute is a dict like object serialize each key and value recursively.
|
|
63
|
+
- It the attribute is an Enum instance use its value.
|
|
64
|
+
- If the attribute is a datetime or date instance use its isoformat() representation.
|
|
65
|
+
- Otherwise create a recursive call to serialize() the attributes of the object.
|
|
66
|
+
|
|
67
|
+
Note about __attribute_serializer__():
|
|
68
|
+
- calling __attribute_serializer__() if supported by the object is the first thing done.
|
|
69
|
+
This allows to override the standard behavior.
|
|
70
|
+
- It receives three parameter:
|
|
71
|
+
- name : the name of the attribute
|
|
72
|
+
- value: the value of the attribute
|
|
73
|
+
- a function to call to serialize recursively what's inside the attribute if needed. This function must accept
|
|
74
|
+
these three parameters:
|
|
75
|
+
- name of the attribute
|
|
76
|
+
- value of the attribute
|
|
77
|
+
- a function to call to serialize recursively what's inside the attribute if needed.
|
|
78
|
+
The function must return a value or None which will be used as the serialized
|
|
79
|
+
value of the attribute. It can also raise a StopIteration exception to skip the attribute.
|
|
80
|
+
- an attribute_serializer function can also be passed directly to the serialize() function. In this
|
|
81
|
+
case the one passed as parameter has precedence over the one define on the object. The main difference is
|
|
82
|
+
that the one passed as parameter will receive all attributes of all objects being serialized while the one
|
|
83
|
+
defined on the object will only receive the attributes of that object.
|
|
84
|
+
|
|
85
|
+
Note on serialization key order:
|
|
86
|
+
- It is possible to define a listof attributes to serialize (which allows to include attributes that starts with an underscore (_)) with
|
|
87
|
+
a specific order by three ways listed below in their order of precedence:
|
|
88
|
+
|
|
89
|
+
- passing a serialization_key_order parameter to the serialize() function.
|
|
90
|
+
- defining a __serialization_key_order__ attribute on the object to serialize.
|
|
91
|
+
- Using the SerializableField metadata class to mark attributes for serialization and define their order.
|
|
92
|
+
|
|
93
|
+
- It must be a sequence of strings with the attribute names in the order they must be serialized.
|
|
94
|
+
- If defined only the attributes in that list will be serialized, all other attributes will be skipped.
|
|
95
|
+
|
|
96
|
+
Note on SerializableField:
|
|
97
|
+
- You can use the SerializableField metadata class to mark attributes for serialization and define their order.
|
|
98
|
+
Usage example:
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
from typing import Annotated
|
|
102
|
+
class MyClass():
|
|
103
|
+
attr1: Annotated[int, JsonField(order=1)]
|
|
104
|
+
attr2: Annotated[str, JsonField()] # no order, will be after attr1
|
|
105
|
+
attr3: float # not marked, will be ignored
|
|
106
|
+
attr4: Annotated[bool, JsonField(order=0)] # will be first
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Note on serialization of unknown types:
|
|
110
|
+
- For some object the serialization can go too deep into the object graph producing unwanted data in the
|
|
111
|
+
serialization. To avoid this use a custom __attribute_serializer__() method to control the serialization
|
|
112
|
+
of such attributes.
|
|
113
|
+
"""
|
|
114
|
+
recurser = _Recurser(
|
|
115
|
+
not_use_key_order=not_use_key_order,
|
|
116
|
+
serialization_key_order=serialization_key_order,
|
|
117
|
+
attribute_serializer=attribute_serializer,
|
|
118
|
+
)
|
|
119
|
+
return recurser(obj)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def is_primitive(obj: Any) -> bool:
|
|
123
|
+
"""test obj that serialize to themselves"""
|
|
124
|
+
return isinstance(
|
|
125
|
+
obj,
|
|
126
|
+
(int, float, str, bool, type(None), np.integer, np.floating),
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def is_sequence(obj: Any) -> bool:
|
|
131
|
+
"""test if obj is a sequence (list, tuple, etc...) but not a string in the most general way"""
|
|
132
|
+
try:
|
|
133
|
+
len(obj)
|
|
134
|
+
obj[0:0]
|
|
135
|
+
return not isinstance(obj, str)
|
|
136
|
+
except KeyError:
|
|
137
|
+
return False
|
|
138
|
+
except TypeError:
|
|
139
|
+
return False # TypeError: object is not iterable
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def is_dict(obj: Any) -> bool:
|
|
143
|
+
"""test if obj is a dict like object in the most general way"""
|
|
144
|
+
return isinstance(obj, Mapping)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def serialize_leaf(obj: Any) -> Any:
|
|
148
|
+
"""try to serialize leaf types (primitive, enum, datetime, date, np.bool_)"""
|
|
149
|
+
if is_primitive(obj):
|
|
150
|
+
if isinstance(obj, np.integer):
|
|
151
|
+
return int(obj)
|
|
152
|
+
if isinstance(obj, np.floating):
|
|
153
|
+
return float(obj)
|
|
154
|
+
return obj
|
|
155
|
+
|
|
156
|
+
if isinstance(obj, Enum):
|
|
157
|
+
return obj.value
|
|
158
|
+
|
|
159
|
+
if isinstance(obj, datetime):
|
|
160
|
+
return obj.isoformat()
|
|
161
|
+
|
|
162
|
+
if isinstance(obj, date):
|
|
163
|
+
return obj.isoformat()
|
|
164
|
+
|
|
165
|
+
if isinstance(obj, np.bool_):
|
|
166
|
+
return bool(obj)
|
|
167
|
+
|
|
168
|
+
return None # not a leaf type except if it is None
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class _Recurser:
|
|
172
|
+
"""
|
|
173
|
+
Intenal class not meant to be used directly.
|
|
174
|
+
Performs the serialization with its onw anti_loop_list.
|
|
175
|
+
"""
|
|
176
|
+
|
|
177
|
+
_logger = logging.getLogger(__name__)
|
|
178
|
+
_not_use_key_order: bool
|
|
179
|
+
""" If True, do not use the __serialization_key_order__ attribute of objects during serialization."""
|
|
180
|
+
_anti_loop_list: list[str]
|
|
181
|
+
""" List of object ids currently being serialized to prevent recursion."""
|
|
182
|
+
_serialization_key_order: Sequence[str] | None
|
|
183
|
+
""" Optional key order to use for serialization instead of the object's __serialization_key_order__ attribute."""
|
|
184
|
+
_attribute_serializer: Callable[[str, Any, Callable[[Any], Any]], Any] | None
|
|
185
|
+
""" Optional attribute serializer function to use for all objects being serialized."""
|
|
186
|
+
|
|
187
|
+
def __init__(
|
|
188
|
+
self,
|
|
189
|
+
*,
|
|
190
|
+
serialization_key_order: Sequence[str] | None = None,
|
|
191
|
+
not_use_key_order: bool = False,
|
|
192
|
+
attribute_serializer: (
|
|
193
|
+
Callable[[str, Any, Callable[[Any], Any]], Any] | None
|
|
194
|
+
) = None,
|
|
195
|
+
) -> None:
|
|
196
|
+
self._not_use_key_order = not_use_key_order
|
|
197
|
+
self._serialization_key_order = serialization_key_order
|
|
198
|
+
self._anti_loop_list = []
|
|
199
|
+
self._attribute_serializer = attribute_serializer
|
|
200
|
+
|
|
201
|
+
def __call__(
|
|
202
|
+
self,
|
|
203
|
+
obj: Any,
|
|
204
|
+
) -> Any:
|
|
205
|
+
"""Entry point for serialization."""
|
|
206
|
+
# build the call parameters for the __serialize__ method
|
|
207
|
+
pars: dict = {}
|
|
208
|
+
|
|
209
|
+
# if object as a __serialize__ method we use it for the serialization
|
|
210
|
+
serialize_method = getattr(obj, "__serialize__", None)
|
|
211
|
+
if serialize_method is not None and callable(serialize_method):
|
|
212
|
+
return cast(Any, serialize_method())
|
|
213
|
+
|
|
214
|
+
# if there is an attribute_serializer function passed as parameter or if the object has
|
|
215
|
+
# a __attribute_serializer__ method we use it for the serialization of the object
|
|
216
|
+
# attributes when we will traverse them. The one passed as parameter has precedence.
|
|
217
|
+
if self._attribute_serializer is not None:
|
|
218
|
+
pars["attribute_serializer"] = self._attribute_serializer
|
|
219
|
+
else:
|
|
220
|
+
get_attr_serializer_method = getattr(obj, "__attribute_serializer__", None)
|
|
221
|
+
if get_attr_serializer_method is not None and callable(
|
|
222
|
+
get_attr_serializer_method
|
|
223
|
+
):
|
|
224
|
+
pars["attribute_serializer"] = get_attr_serializer_method
|
|
225
|
+
|
|
226
|
+
# determine the key order to use for serialization if any
|
|
227
|
+
if not self._not_use_key_order:
|
|
228
|
+
|
|
229
|
+
key_order: Sequence[str] | None = self._serialization_key_order
|
|
230
|
+
# if the object has a serialization key order list there is no
|
|
231
|
+
# serialization_key_order parameter passed in the constructor we use it
|
|
232
|
+
if key_order is None:
|
|
233
|
+
key_order = getattr(obj, "__serialization_key_order__", None)
|
|
234
|
+
# if no key order list has been found yet we look if the object attribute are marked with SerializableField
|
|
235
|
+
if key_order is None:
|
|
236
|
+
if candidate := self.__class__.get_annotated_serialization_order(
|
|
237
|
+
obj.__class__
|
|
238
|
+
):
|
|
239
|
+
key_order = candidate
|
|
240
|
+
pars["key_order"] = key_order
|
|
241
|
+
return self.serialize(obj, **pars)
|
|
242
|
+
|
|
243
|
+
@staticmethod
|
|
244
|
+
def get_annotated_serialization_order(target_class: type) -> list[str]:
|
|
245
|
+
"""
|
|
246
|
+
scans the class and select attributes whose type is declared as Annotated with SerializableField metadata (see usage below).
|
|
247
|
+
It returns the list of attribute names sorted by the order defined in SerializableField.order or by
|
|
248
|
+
declaration order if order is None.
|
|
249
|
+
|
|
250
|
+
"""
|
|
251
|
+
# Important: include_extras=True pour conserver Annotated[..., meta]
|
|
252
|
+
hints: dict[str, Any] = get_type_hints(target_class, include_extras=True)
|
|
253
|
+
|
|
254
|
+
selected: list[tuple[int, int, str]] = []
|
|
255
|
+
decl_index = 0
|
|
256
|
+
|
|
257
|
+
for name, ann in hints.items():
|
|
258
|
+
if get_origin(ann) is Annotated:
|
|
259
|
+
_, *meta = get_args(ann)
|
|
260
|
+
tag = next((m for m in meta if isinstance(m, SerializableField)), None)
|
|
261
|
+
if tag is not None:
|
|
262
|
+
# - ordre explicite si fourni
|
|
263
|
+
# - sinon on garde l'ordre de déclaration via decl_index
|
|
264
|
+
sort_order = tag.order if tag.order is not None else 10**9
|
|
265
|
+
selected.append((sort_order, decl_index, name))
|
|
266
|
+
decl_index += 1
|
|
267
|
+
|
|
268
|
+
selected.sort()
|
|
269
|
+
return [name for _ord, _i, name in selected]
|
|
270
|
+
|
|
271
|
+
def _make_id(self, obj: Any) -> str:
|
|
272
|
+
obj_class = type(obj)
|
|
273
|
+
return f"{obj_class.__module__}.{obj_class.__name__}_{id(obj)}"
|
|
274
|
+
|
|
275
|
+
def serialize(
|
|
276
|
+
self,
|
|
277
|
+
obj: Any,
|
|
278
|
+
*,
|
|
279
|
+
attribute_serializer: Callable[..., Any] | None = None,
|
|
280
|
+
key_order: Sequence[str] | None = None,
|
|
281
|
+
) -> Any:
|
|
282
|
+
"""Make the recursives call for the __serialize__() method"""
|
|
283
|
+
|
|
284
|
+
# First handle objects that can be directly serialized - only on the first call
|
|
285
|
+
# subsequent recursive calls will be handled this case inside the attributre traversal
|
|
286
|
+
if obj is None:
|
|
287
|
+
return None
|
|
288
|
+
direct_res = serialize_leaf(obj)
|
|
289
|
+
if direct_res is not None:
|
|
290
|
+
return direct_res
|
|
291
|
+
|
|
292
|
+
# Now handle iterable like objects
|
|
293
|
+
if is_sequence(obj) or isinstance(obj, (set, frozenset)):
|
|
294
|
+
return [self(elem) for elem in obj]
|
|
295
|
+
|
|
296
|
+
if is_dict(obj):
|
|
297
|
+
return {self(k): self(v) for k, v in obj.items()}
|
|
298
|
+
|
|
299
|
+
# Now we are going to traverse the object attributes
|
|
300
|
+
# we start by checking for recursion
|
|
301
|
+
obj_id_str = self._make_id(obj)
|
|
302
|
+
if obj_id_str in self._anti_loop_list:
|
|
303
|
+
print(f"Recursion on {obj_id_str}")
|
|
304
|
+
rep: str
|
|
305
|
+
if "__repr__" in obj.__class__.__dict__:
|
|
306
|
+
rep = obj.__repr__()
|
|
307
|
+
else:
|
|
308
|
+
rep = obj_id_str
|
|
309
|
+
return f"{rep}"
|
|
310
|
+
self._anti_loop_list.append(obj_id_str)
|
|
311
|
+
|
|
312
|
+
# Traverse attributes
|
|
313
|
+
res: dict[str, Any] = {}
|
|
314
|
+
for name, value in inspect.getmembers(obj):
|
|
315
|
+
# Try to calling object's __attribute_serializer__() method if any
|
|
316
|
+
res_value: Any = None
|
|
317
|
+
if attribute_serializer is not None:
|
|
318
|
+
try:
|
|
319
|
+
res_value = attribute_serializer(name, value, self)
|
|
320
|
+
except StopIteration:
|
|
321
|
+
# means that the attribute must be skipped
|
|
322
|
+
continue
|
|
323
|
+
if res_value is None:
|
|
324
|
+
# reject class attributes
|
|
325
|
+
if inspect.isclass(value):
|
|
326
|
+
continue
|
|
327
|
+
# reject attributes whose name starts with _ unless they are in the key_order list
|
|
328
|
+
if name.startswith("_") and (key_order is None or name not in key_order):
|
|
329
|
+
continue
|
|
330
|
+
|
|
331
|
+
# reject callables
|
|
332
|
+
if (
|
|
333
|
+
inspect.ismethod(value)
|
|
334
|
+
or inspect.isbuiltin(value)
|
|
335
|
+
or inspect.ismethodwrapper(value)
|
|
336
|
+
or inspect.isroutine(value)
|
|
337
|
+
):
|
|
338
|
+
continue
|
|
339
|
+
|
|
340
|
+
# if key_order is defined we skip attributes not in the list
|
|
341
|
+
if key_order is not None and name not in key_order:
|
|
342
|
+
continue
|
|
343
|
+
|
|
344
|
+
self._logger.debug(
|
|
345
|
+
f"Processing attribute {name} with value type {type(value)}"
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
# test if the attribute is directly serializable
|
|
349
|
+
if res_value is None:
|
|
350
|
+
res_value = serialize_leaf(value)
|
|
351
|
+
# we don't know how to serialize this attribute so we to stringify it
|
|
352
|
+
if res_value is None:
|
|
353
|
+
res_value = self(value)
|
|
354
|
+
|
|
355
|
+
res[name] = res_value
|
|
356
|
+
|
|
357
|
+
self._anti_loop_list.pop()
|
|
358
|
+
|
|
359
|
+
if key_order is not None:
|
|
360
|
+
res = OrderedDict(
|
|
361
|
+
sorted(
|
|
362
|
+
[item for item in res.items() if item[0] in key_order],
|
|
363
|
+
key=lambda item: key_order.index(item[0]),
|
|
364
|
+
)
|
|
365
|
+
)
|
|
366
|
+
return res
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: pycraftbox-serialization
|
|
3
|
+
Version: 4.0.0
|
|
4
|
+
Summary: Object and dataclass serialization utilities for pycraftbox
|
|
5
|
+
Project-URL: Homepage, https://gitlab.com/erch/pycraftbox
|
|
6
|
+
Project-URL: Repository, https://gitlab.com/erch/pycraftbox
|
|
7
|
+
Project-URL: Issues, https://gitlab.com/erch/pycraftbox/-/issues
|
|
8
|
+
Requires-Python: >=3.12
|
|
9
|
+
Requires-Dist: numpy>=2.2.1
|
|
10
|
+
Requires-Dist: pycraftbox-core<5,>=4
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
pycraftbox/serialization/__init__.py,sha256=yYZ9sqIBVDAhZdGx3cs3PNc7SgS6imo7ndssCuCDVlY,461
|
|
2
|
+
pycraftbox/serialization/base_dataclass.py,sha256=UFVMfrUO7eEP3sGpx8GsRrwMXWVb9fHmuXOpYOaza8c,12651
|
|
3
|
+
pycraftbox/serialization/serializer.py,sha256=H5XYGC5FIaF0pA5CDwEsXdfdraw6v8yhd3OTvAkqdjI,15638
|
|
4
|
+
pycraftbox_serialization-4.0.0.dist-info/METADATA,sha256=icq3hltoVvQdS9Se9ALdE9VT0W31X-K4g9s5SFlQ3F8,409
|
|
5
|
+
pycraftbox_serialization-4.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
6
|
+
pycraftbox_serialization-4.0.0.dist-info/RECORD,,
|