-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathmsgpack_serializer.py
More file actions
41 lines (33 loc) · 942 Bytes
/
msgpack_serializer.py
File metadata and controls
41 lines (33 loc) · 942 Bytes
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
import msgpack
from PythonBridge.object_registry import registry
primitive_types = [
type(None),
bool,
int,
bytes,
str,
dict,
list,
memoryview,
bytearray]
mapper = {}
def addMapping(key_type, mapping_function):
mapper[key_type] = mapping_function
class MsgPackSerializer:
def __init__(self):
self.primitive_types = primitive_types
def mapper(self):
return mapper
def default(self, obj):
if type(obj) in self.primitive_types:
return obj
if type(obj) in self.mapper():
return self.mapper()[type(obj)](obj)
return {
'__pyclass__': type(obj).__name__,
'__pyid__': registry().register(obj)
}
def serialize(self, obj):
return msgpack.packb(obj, default=self.default, use_bin_type=True)
def deserialize(self, binary):
return msgpack.unpackb(binary, raw=False)