8000 Add ext_type example to README. · zhurs/msgpack-python@84dc99c · GitHub
[go: up one dir, main page]

Skip to content

Commit 84dc99c

Browse files
committed
Add ext_type example to README.
1 parent 0d5c58b commit 84dc99c

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

README.rst

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -143,10 +143,27 @@ key-value pairs.
143143
Extended types
144144
^^^^^^^^^^^^^^^
145145

146-
It is also possible to pack/unpack custom data types using the msgpack feature
147-
of "extended types". For example, msgpack-pypy uses it to provide very fast serialization of int/float lists on top of PyPy (experimental for now):
148-
149-
https://bitbucket.org/antocuni/msgpack-pypy/src/default/msgpack_pypy.py
146+
It is also possible to pack/unpack custom data types using the msgpack 2.0 feature.
147+
148+
>>> import msgpack
149+
>>> import array
150+
>>> def default(obj):
151+
... if isinstance(obj, array.array) and obj.typecode == 'd':
152+
... return msgpack.ExtType(42, obj.tostring())
153+
... raise TypeError("Unknown type: %r" % (obj,))
154+
...
155+
>>> def ext_hook(code, data):
156+
... if code == 42:
157+
... a = array.array('d')
158+
... a.fromstring(data)
159+
... return a
160+
... return ExtType(code, data)
161+
...
162+
>>> data = array.array('d', [1.2, 3.4])
163+
>>> packed = msgpack.packb(data, default=default)
164+
>>> unpacked = msgpack.unpackb(packed, ext_hook=ext_hook)
165+
>>> data == unpacked
166+
True
150167

151168

152169
Advanced unpacking control

0 commit comments

Comments
 (0)
0