mirror of
https://github.com/msgpack/msgpack-python.git
synced 2025-11-02 02:20:54 +00:00
add support for extended types: you can now pack/unpack custom python objects by subclassing Packer and Unpacker
This commit is contained in:
parent
f45d7b4e2d
commit
d61097511a
2 changed files with 108 additions and 47 deletions
24
test/test_extension.py
Normal file
24
test/test_extension.py
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import array
|
||||
import msgpack
|
||||
|
||||
def test_extension_type():
|
||||
class MyPacker(msgpack.Packer):
|
||||
def handle_extended_type(self, obj):
|
||||
if isinstance(obj, array.array):
|
||||
fmt = "ext 32"
|
||||
typecode = 123 # application specific typecode
|
||||
data = obj.tostring()
|
||||
return fmt, typecode, data
|
||||
|
||||
class MyUnpacker(msgpack.Unpacker):
|
||||
def handle_extended_type(self, typecode, data):
|
||||
assert typecode == 123
|
||||
obj = array.array('d')
|
||||
obj.fromstring(data)
|
||||
return obj
|
||||
|
||||
obj = [42, 'hello', array.array('d', [1.1, 2.2, 3.3])]
|
||||
s = msgpack.packb(obj, MyPacker)
|
||||
obj2 = msgpack.unpackb(s, MyUnpacker)
|
||||
assert obj == obj2
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue