summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorINADA Naoki <inada-n@klab.com>2013-10-20 23:27:32 +0900
committerINADA Naoki <inada-n@klab.com>2013-10-20 23:27:32 +0900
commit84dc99c894be82b7a8c3708a3554888a6133b33b (patch)
treeb1e4e1847de64f2af1eaf27ca52d75d76b61f8d9
parent0d5c58bd517caddd6b62a8931f6833e2a3add283 (diff)
downloadmsgpack-python-84dc99c894be82b7a8c3708a3554888a6133b33b.tar.gz
Add ext_type example to README.
-rw-r--r--README.rst25
1 files changed, 21 insertions, 4 deletions
diff --git a/README.rst b/README.rst
index 600d7f7..99fb923 100644
--- a/README.rst
+++ b/README.rst
@@ -143,10 +143,27 @@ key-value pairs.
Extended types
^^^^^^^^^^^^^^^
-It is also possible to pack/unpack custom data types using the msgpack feature
-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):
-
-https://bitbucket.org/antocuni/msgpack-pypy/src/default/msgpack_pypy.py
+It is also possible to pack/unpack custom data types using the msgpack 2.0 feature.
+
+ >>> import msgpack
+ >>> import array
+ >>> def default(obj):
+ ... if isinstance(obj, array.array) and obj.typecode == 'd':
+ ... return msgpack.ExtType(42, obj.tostring())
+ ... raise TypeError("Unknown type: %r" % (obj,))
+ ...
+ >>> def ext_hook(code, data):
+ ... if code == 42:
+ ... a = array.array('d')
+ ... a.fromstring(data)
+ ... return a
+ ... return ExtType(code, data)
+ ...
+ >>> data = array.array('d', [1.2, 3.4])
+ >>> packed = msgpack.packb(data, default=default)
+ >>> unpacked = msgpack.unpackb(packed, ext_hook=ext_hook)
+ >>> data == unpacked
+ True
Advanced unpacking control