Skip to main content

MessagePack (de)serializer.

Project description

Build Status Documentation Status

What’s this

MessagePack is an efficient binary serialization format. It lets you exchange data among multiple languages like JSON. But it’s faster and smaller. This package provides CPython bindings for reading and writing MessagePack data.

Very important notes for existing users

PyPI package name

TL;DR: When upgrading from msgpack-0.4 or earlier, don’t do pip install -U msgpack-python. Do pip uninstall msgpack-python; pip install msgpack instead.

Package name on PyPI was changed to msgpack from 0.5. I upload transitional package (msgpack-python 0.5 which depending on msgpack) for smooth transition from msgpack-python to msgpack.

Sadly, this doesn’t work for upgrade install. After pip install -U msgpack-python, msgpack is removed and import msgpack fail.

Deprecating encoding option

encoding and unicode_errors options are deprecated.

In case of packer, use UTF-8 always. Storing other than UTF-8 is not recommended.

For backward compatibility, you can use use_bin_type=False and pack bytes object into msgpack raw type.

In case of unpacker, there is new raw option. It is True by default for backward compatibility, but it is changed to False in near future. You can use raw=False instead of encoding='utf-8'.

Planned backward incompatible changes

When msgpack 1.0, I planning these breaking changes:

  • packer and unpacker: Remove encoding and unicode_errors option.

  • packer: Change default of use_bin_type option from False to True.

  • unpacker: Change default of raw option from True to False.

  • unpacker: Reduce all max_xxx_len options for typical usage.

  • unpacker: Remove write_bytes option from all methods.

To avoid these breaking changes breaks your application, please:

  • Don’t use deprecated options.

  • Pass use_bin_type and raw options explicitly.

  • If your application handle large (>1MB) data, specify max_xxx_len options too.

Install

$ pip install msgpack

PyPy

msgpack provides a pure Python implementation. PyPy can use this.

Windows

When you can’t use a binary distribution, you need to install Visual Studio or Windows SDK on Windows. Without extension, using pure Python implementation on CPython runs slowly.

For Python 2.7, Microsoft Visual C++ Compiler for Python 2.7 is recommended solution.

For Python 3.5, Microsoft Visual Studio 2015 Community Edition or Express Edition can be used to build extension module.

How to use

One-shot pack & unpack

Use packb for packing and unpackb for unpacking. msgpack provides dumps and loads as an alias for compatibility with json and pickle.

pack and dump packs to a file-like object. unpack and load unpacks from a file-like object.

>>> import msgpack
>>> msgpack.packb([1, 2, 3], use_bin_type=True)
'\x93\x01\x02\x03'
>>> msgpack.unpackb(_, raw=False)
[1, 2, 3]

unpack unpacks msgpack’s array to Python’s list, but can also unpack to tuple:

>>> msgpack.unpackb(b'\x93\x01\x02\x03', use_list=False, raw=False)
(1, 2, 3)

You should always specify the use_list keyword argument for backward compatibility. See performance issues relating to use_list option below.

Read the docstring for other options.

Streaming unpacking

Unpacker is a “streaming unpacker”. It unpacks multiple objects from one stream (or from bytes provided through its feed method).

import msgpack
from io import BytesIO

buf = BytesIO()
for i in range(100):
   buf.write(msgpack.packb(range(i), use_bin_type=True))

buf.seek(0)

unpacker = msgpack.Unpacker(buf, raw=False)
for unpacked in unpacker:
    print(unpacked)

Packing/unpacking of custom data type

It is also possible to pack/unpack custom data types. Here is an example for datetime.datetime.

import datetime
import msgpack

useful_dict = {
    "id": 1,
    "created": datetime.datetime.now(),
}

def decode_datetime(obj):
    if b'__datetime__' in obj:
        obj = datetime.datetime.strptime(obj["as_str"], "%Y%m%dT%H:%M:%S.%f")
    return obj

def encode_datetime(obj):
    if isinstance(obj, datetime.datetime):
        return {'__datetime__': True, 'as_str': obj.strftime("%Y%m%dT%H:%M:%S.%f")}
    return obj


packed_dict = msgpack.packb(useful_dict, default=encode_datetime, use_bin_type=True)
this_dict_again = msgpack.unpackb(packed_dict, object_hook=decode_datetime, raw=False)

Unpacker’s object_hook callback receives a dict; the object_pairs_hook callback may instead be used to receive a list of key-value pairs.

Extended types

It is also possible to pack/unpack custom data types using the ext type.

>>> 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, use_bin_type=True)
>>> unpacked = msgpack.unpackb(packed, ext_hook=ext_hook, raw=False)
>>> data == unpacked
True

Advanced unpacking control

As an alternative to iteration, Unpacker objects provide unpack, skip, read_array_header and read_map_header methods. The former two read an entire message from the stream, respectively de-serialising and returning the result, or ignoring it. The latter two methods return the number of elements in the upcoming container, so that each element in an array, or key-value pair in a map, can be unpacked or skipped individually.

Each of these methods may optionally write the packed data it reads to a callback function:

from io import BytesIO

def distribute(unpacker, get_worker):
    nelems = unpacker.read_map_header()
    for i in range(nelems):
        # Select a worker for the given key
        key = unpacker.unpack()
        worker = get_worker(key)

        # Send the value as a packed message to worker
        bytestream = BytesIO()
        unpacker.skip(bytestream.write)
        worker.send(bytestream.getvalue())

Notes

string and binary type

Early versions of msgpack didn’t distinguish string and binary types (like Python 1). The type for representing both string and binary types was named raw.

For backward compatibility reasons, msgpack-python will still default all strings to byte strings, unless you specify the use_bin_type=True option in the packer. If you do so, it will use a non-standard type called bin to serialize byte arrays, and raw becomes to mean str. If you want to distinguish bin and raw in the unpacker, specify raw=False.

Note that Python 2 defaults to byte-arrays over Unicode strings:

>>> import msgpack
>>> msgpack.unpackb(msgpack.packb([b'spam', u'eggs']))
['spam', 'eggs']
>>> msgpack.unpackb(msgpack.packb([b'spam', u'eggs'], use_bin_type=True),
                    raw=False)
['spam', u'eggs']

This is the same code in Python 3 (same behaviour, but Python 3 has a different default):

>>> import msgpack
>>> msgpack.unpackb(msgpack.packb([b'spam', u'eggs']))
[b'spam', b'eggs']
>>> msgpack.unpackb(msgpack.packb([b'spam', u'eggs'], use_bin_type=True),
                    raw=False)
[b'spam', 'eggs']

ext type

To use the ext type, pass msgpack.ExtType object to packer.

>>> import msgpack
>>> packed = msgpack.packb(msgpack.ExtType(42, b'xyzzy'))
>>> msgpack.unpackb(packed)
ExtType(code=42, data='xyzzy')

You can use it with default and ext_hook. See below.

Note about performance

GC

CPython’s GC starts when growing allocated object. This means unpacking may cause useless GC. You can use gc.disable() when unpacking large message.

use_list option

List is the default sequence type of Python. But tuple is lighter than list. You can use use_list=False while unpacking when performance is important.

Python’s dict can’t use list as key and MessagePack allows array for key of mapping. use_list=False allows unpacking such message. Another way to unpacking such object is using object_pairs_hook.

Development

Test

MessagePack uses pytest for testing. Run test with following command:

$ make test

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

msgpack-0.5.6.tar.gz (138.3 kB view details)

Uploaded Source

Built Distributions

msgpack-0.5.6-cp36-cp36m-win_amd64.whl (85.8 kB view details)

Uploaded CPython 3.6m Windows x86-64

msgpack-0.5.6-cp36-cp36m-win32.whl (77.3 kB view details)

Uploaded CPython 3.6m Windows x86

msgpack-0.5.6-cp36-cp36m-manylinux1_x86_64.whl (315.7 kB view details)

Uploaded CPython 3.6m

msgpack-0.5.6-cp36-cp36m-manylinux1_i686.whl (298.9 kB view details)

Uploaded CPython 3.6m

msgpack-0.5.6-cp35-cp35m-win_amd64.whl (85.2 kB view details)

Uploaded CPython 3.5m Windows x86-64

msgpack-0.5.6-cp35-cp35m-win32.whl (76.6 kB view details)

Uploaded CPython 3.5m Windows x86

msgpack-0.5.6-cp35-cp35m-manylinux1_x86_64.whl (309.3 kB view details)

Uploaded CPython 3.5m

msgpack-0.5.6-cp35-cp35m-manylinux1_i686.whl (290.6 kB view details)

Uploaded CPython 3.5m

msgpack-0.5.6-cp27-cp27mu-manylinux1_x86_64.whl (295.8 kB view details)

Uploaded CPython 2.7mu

msgpack-0.5.6-cp27-cp27mu-manylinux1_i686.whl (279.1 kB view details)

Uploaded CPython 2.7mu

msgpack-0.5.6-cp27-cp27m-win_amd64.whl (84.4 kB view details)

Uploaded CPython 2.7m Windows x86-64

msgpack-0.5.6-cp27-cp27m-win32.whl (75.7 kB view details)

Uploaded CPython 2.7m Windows x86

msgpack-0.5.6-cp27-cp27m-manylinux1_x86_64.whl (295.8 kB view details)

Uploaded CPython 2.7m

msgpack-0.5.6-cp27-cp27m-manylinux1_i686.whl (279.1 kB view details)

Uploaded CPython 2.7m

File details

Details for the file msgpack-0.5.6.tar.gz.

File metadata

  • Download URL: msgpack-0.5.6.tar.gz
  • Upload date:
  • Size: 138.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for msgpack-0.5.6.tar.gz
Algorithm Hash digest
SHA256 0ee8c8c85aa651be3aa0cd005b5931769eaa658c948ce79428766f1bd46ae2c3
MD5 9dfceb24c6e4e7de032687ee5a7ef4d6
BLAKE2b-256 f3b69affbea179c3c03a0eb53515d9ce404809a122f76bee8fc8c6ec9497f51f

See more details on using hashes here.

File details

Details for the file msgpack-0.5.6-cp36-cp36m-win_amd64.whl.

File metadata

File hashes

Hashes for msgpack-0.5.6-cp36-cp36m-win_amd64.whl
Algorithm Hash digest
SHA256 31a98047355d34d047fcdb55b09cb19f633cf214c705a765bd745456c142130c
MD5 5cfec7587e3275ab8f7db004c3fe0395
BLAKE2b-256 0481c6363198f24ec1c56e5c48ce685cb532e175125adade0cdb181c8c5fea6e

See more details on using hashes here.

File details

Details for the file msgpack-0.5.6-cp36-cp36m-win32.whl.

File metadata

File hashes

Hashes for msgpack-0.5.6-cp36-cp36m-win32.whl
Algorithm Hash digest
SHA256 8acc8910218555044e23826980b950e96685dc48124a290c86f6f41a296ea172
MD5 f026394b369be76a2ccab2dc01d09d34
BLAKE2b-256 93d442b64ede2bb27a7db3f0177789ba975d5a07e463b71089d3bbb5953de170

See more details on using hashes here.

File details

Details for the file msgpack-0.5.6-cp36-cp36m-manylinux1_x86_64.whl.

File metadata

File hashes

Hashes for msgpack-0.5.6-cp36-cp36m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 f86642d60dca13e93260187d56c2bef2487aa4d574a669e8ceefcf9f4c26fd00
MD5 0101b236ea54f7e7312c2bdd75013c56
BLAKE2b-256 224edcf124fd97e5f5611123d6ad9f40ffd6eb979d1efdc1049e28a795672fcd

See more details on using hashes here.

File details

Details for the file msgpack-0.5.6-cp36-cp36m-manylinux1_i686.whl.

File metadata

File hashes

Hashes for msgpack-0.5.6-cp36-cp36m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 0bae5d1538c5c6a75642f75a1781f3ac2275d744a92af1a453c150da3446138b
MD5 3330dd9de8ad3935767c9a100dba5f02
BLAKE2b-256 9b9706fe1505fc7813d226e83970321a279acca54a90bae36bda6a61b0e2cd89

See more details on using hashes here.

File details

Details for the file msgpack-0.5.6-cp35-cp35m-win_amd64.whl.

File metadata

File hashes

Hashes for msgpack-0.5.6-cp35-cp35m-win_amd64.whl
Algorithm Hash digest
SHA256 22d9c929d1d539f37da3d1b0e16270fa9d46107beab8c0d4d2bddffffe895cee
MD5 5525137b69953aff04aa5fc242a9d631
BLAKE2b-256 9a4f7c1188ff64148b36d0d7ddeaba0f6e8e2fb7a46cd942f3543420b714a89f

See more details on using hashes here.

File details

Details for the file msgpack-0.5.6-cp35-cp35m-win32.whl.

File metadata

File hashes

Hashes for msgpack-0.5.6-cp35-cp35m-win32.whl
Algorithm Hash digest
SHA256 0b3b1773d2693c70598585a34ca2715873ba899565f0a7c9a1545baef7e7fbdc
MD5 b459daef1996b4512be7350dfff2e88f
BLAKE2b-256 a8790793bfc6e7a01b622ed8d8ac24dfbbe519819a7e3025d10e2a231b6ae097

See more details on using hashes here.

File details

Details for the file msgpack-0.5.6-cp35-cp35m-manylinux1_x86_64.whl.

File metadata

File hashes

Hashes for msgpack-0.5.6-cp35-cp35m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 e274cd4480d8c76ec467a85a9c6635bbf2258f0649040560382ab58cabb44bcf
MD5 abec03bf3454cd0e9e0d36428bae5e9a
BLAKE2b-256 08725a01d2a6a894e7f6966b0038445c748d7a16754cceb0e988699269d8152a

See more details on using hashes here.

File details

Details for the file msgpack-0.5.6-cp35-cp35m-manylinux1_i686.whl.

File metadata

File hashes

Hashes for msgpack-0.5.6-cp35-cp35m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 ab189a6365be1860a5ecf8159c248f12d33f79ea799ae9695fa6a29896dcf1d4
MD5 d24e279c84063b3fd4805d474df1e321
BLAKE2b-256 6e0fa05feba90772d67a3ec0680da76d90e267ba82ff541e63b5b836518f8f4d

See more details on using hashes here.

File details

Details for the file msgpack-0.5.6-cp27-cp27mu-manylinux1_x86_64.whl.

File metadata

File hashes

Hashes for msgpack-0.5.6-cp27-cp27mu-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 2ff43e3247a1e11d544017bb26f580a68306cec7a6257d8818893c1fda665f42
MD5 c09bb66349c934a72f076a6150b535d6
BLAKE2b-256 ff0d536fd0b2808dfbc67de46168dc706b5c9f9a1f5a803d96b8bc562a6d96c2

See more details on using hashes here.

File details

Details for the file msgpack-0.5.6-cp27-cp27mu-manylinux1_i686.whl.

File metadata

File hashes

Hashes for msgpack-0.5.6-cp27-cp27mu-manylinux1_i686.whl
Algorithm Hash digest
SHA256 8767eb0032732c3a0da92cbec5ac186ef89a3258c6edca09161472ca0206c45f
MD5 efeb636ffd017aa67e8a81e160e13024
BLAKE2b-256 af1dc5c66d68f104d2e8a8d2a05df468a517428e92c244dfab8cdb18b508b45e

See more details on using hashes here.

File details

Details for the file msgpack-0.5.6-cp27-cp27m-win_amd64.whl.

File metadata

File hashes

Hashes for msgpack-0.5.6-cp27-cp27m-win_amd64.whl
Algorithm Hash digest
SHA256 1369f9edba9500c7a6489b70fdfac773e925342f4531f1e3d4c20ac3173b1ae0
MD5 5258190206d6f3a13957cf34dd676c98
BLAKE2b-256 9dac6025755ec6a11a102ae1db92b064ecba0dfc792bcff5e97acc2939540bcf

See more details on using hashes here.

File details

Details for the file msgpack-0.5.6-cp27-cp27m-win32.whl.

File metadata

File hashes

Hashes for msgpack-0.5.6-cp27-cp27m-win32.whl
Algorithm Hash digest
SHA256 fcea97a352416afcbccd7af9625159d80704a25c519c251c734527329bb20d0e
MD5 8d525d7ddba4dc17b0878abc7fcd9696
BLAKE2b-256 45ae9ece7b2445be3eac195efb3e97764039bc741f6f5ce17bf845000d5f7b29

See more details on using hashes here.

File details

Details for the file msgpack-0.5.6-cp27-cp27m-manylinux1_x86_64.whl.

File metadata

File hashes

Hashes for msgpack-0.5.6-cp27-cp27m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 f8a57cbda46a94ed0db55b73e6ab0c15e78b4ede8690fa491a0e55128d552bb0
MD5 1047af85090da0241c7e5be0eb104cd4
BLAKE2b-256 1e83b280d6f2c9222f7db4f7358840cc6527e16a2daf68ece4a8606d348f58ba

See more details on using hashes here.

File details

Details for the file msgpack-0.5.6-cp27-cp27m-manylinux1_i686.whl.

File metadata

File hashes

Hashes for msgpack-0.5.6-cp27-cp27m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 cfd6535feb0f1cf1c7cdb25773e965cc9f92928244a8c3ef6f8f8a8e1f7ae5c4
MD5 a00883bfa6cf6575194cee20b8e47d08
BLAKE2b-256 6c6df1f973826590f6415bf4e3ef37bc1023ece78f5b116725e2e8dd4e97957b

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page