Skip to main content

MessagePack (de)serializer.

Project description

Build Status Documentation Status

IMPORTANT: Upgrading from msgpack-0.4

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.

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.

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(_)
[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)
(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)
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)

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)
>>> 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 encoding=’utf-8’.

In future version, default value of ``use_bin_type`` will be changed to ``True``. To avoid this change will break your code, you must specify it explicitly even when you want to use old format.

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),
                    encoding='utf-8')
['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),
                    encoding='utf-8')
[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:

$ pytest -v 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.1.tar.gz (142.3 kB view details)

Uploaded Source

Built Distributions

msgpack-0.5.1-cp36-cp36m-win_amd64.whl (85.1 kB view details)

Uploaded CPython 3.6m Windows x86-64

msgpack-0.5.1-cp36-cp36m-win32.whl (76.3 kB view details)

Uploaded CPython 3.6m Windows x86

msgpack-0.5.1-cp36-cp36m-manylinux1_x86_64.whl (322.4 kB view details)

Uploaded CPython 3.6m

msgpack-0.5.1-cp36-cp36m-manylinux1_i686.whl (300.8 kB view details)

Uploaded CPython 3.6m

msgpack-0.5.1-cp35-cp35m-win_amd64.whl (84.4 kB view details)

Uploaded CPython 3.5m Windows x86-64

msgpack-0.5.1-cp35-cp35m-win32.whl (75.7 kB view details)

Uploaded CPython 3.5m Windows x86

msgpack-0.5.1-cp35-cp35m-manylinux1_x86_64.whl (315.8 kB view details)

Uploaded CPython 3.5m

msgpack-0.5.1-cp35-cp35m-manylinux1_i686.whl (296.7 kB view details)

Uploaded CPython 3.5m

msgpack-0.5.1-cp27-cp27mu-manylinux1_x86_64.whl (295.1 kB view details)

Uploaded CPython 2.7mu

msgpack-0.5.1-cp27-cp27mu-manylinux1_i686.whl (278.4 kB view details)

Uploaded CPython 2.7mu

msgpack-0.5.1-cp27-cp27m-win_amd64.whl (82.9 kB view details)

Uploaded CPython 2.7m Windows x86-64

msgpack-0.5.1-cp27-cp27m-win32.whl (74.4 kB view details)

Uploaded CPython 2.7m Windows x86

msgpack-0.5.1-cp27-cp27m-manylinux1_x86_64.whl (295.1 kB view details)

Uploaded CPython 2.7m

msgpack-0.5.1-cp27-cp27m-manylinux1_i686.whl (278.4 kB view details)

Uploaded CPython 2.7m

File details

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

File metadata

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

File hashes

Hashes for msgpack-0.5.1.tar.gz
Algorithm Hash digest
SHA256 f5ebef2049f25da6d7ea53c3f95b4ba175ea9d96fadb60add80fc501a522bcc9
MD5 84c5f8007166c616e803b5c94eb0e8a7
BLAKE2b-256 4503642e1e8e154e26ea1561c275960edee95d28fd0d95b60556bf8d73d7ce7b

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for msgpack-0.5.1-cp36-cp36m-win_amd64.whl
Algorithm Hash digest
SHA256 1dc60a4cfa9433876c4b6e5ab4dc91a2337b2b88fb1d20c54910b0a3f25219bc
MD5 e67ff063b40c1d28b788db81396aefd1
BLAKE2b-256 ea048e712e092ae0bcaf0cee72477632ef166e1ca6525ec49ce14af9568a70de

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for msgpack-0.5.1-cp36-cp36m-win32.whl
Algorithm Hash digest
SHA256 81cdd29e3849b5772ffdee4dee1c83054716f395ff78f502bf0949d1e1409a83
MD5 e1d76171d43f0b4774c81ffc281cc5cf
BLAKE2b-256 ba8563f57d3e4a051ecdab83adf7771973de4052de72ca69912b2c7f700bb9f9

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for msgpack-0.5.1-cp36-cp36m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 6b4334a9785ba1d1019773e5d64cf6842384a053df0cf413336d41b9520a11ba
MD5 271398e6f38d0ecda76087667a3ec826
BLAKE2b-256 d91b78c2d4b9b78a59ac9615b1851d4f769ee3836ac0664f946595239cf2e8bb

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for msgpack-0.5.1-cp36-cp36m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 4c6ccd97a501783b351572f85024892919197b74d61d3b71eebb64210ed07bf7
MD5 f40ab1733a99491607d4282c74573d4f
BLAKE2b-256 9e2854ec1db9672be861f9f64d21edeb7a4cd1402999ceb9862a9239084dfe3b

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for msgpack-0.5.1-cp35-cp35m-win_amd64.whl
Algorithm Hash digest
SHA256 0b91c49693137493f5371428bc3be3e07170d19c509b1d835bea1cdfd52258f5
MD5 7c7371b8733dbd409f508d225da8075c
BLAKE2b-256 46405401c6baaddb0fe968f6abd55e0efaf4429ab7313a46368be44af332d169

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for msgpack-0.5.1-cp35-cp35m-win32.whl
Algorithm Hash digest
SHA256 4f3a1e74ab923adceb5620ad7b5e11ad2418730b6c8d39324595a32a5bed6c08
MD5 abbc41ad4891309dd5a6b7b57ae29228
BLAKE2b-256 204979707f68cf1f63257265899689a21559cc7b138c19003c915535d70330f8

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for msgpack-0.5.1-cp35-cp35m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 d2def7129734a276d21c200c511c5a98adfafb828efc9b1b7513ef94e33e4bdc
MD5 7c973c63946a50ab7313e9a0884f3e4d
BLAKE2b-256 343f8e568475c433a01d068c1402cd2426d71b644402e2b1936630e0134688c2

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for msgpack-0.5.1-cp35-cp35m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 aab92fd798058f0950cf8cb96ec1f7473c1cd7b2c135499d277e3fce054894e7
MD5 a24cd1de988104859be0c40ea64064c9
BLAKE2b-256 b567c7c24909c0c82af53ea7e3307bbd58e0a7849d1ffe17ba3d1205cca034bb

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for msgpack-0.5.1-cp27-cp27mu-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 b396ef2bff9657e134d3c5286c83bc6098223e2c72b30fe05be973714fc96a97
MD5 a6a7182fdc45e84cfd2d991d315800f1
BLAKE2b-256 a385aa3ef9f0b982ca14fe939cbc52192f485db7376f7387888741ecb16c2bfb

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for msgpack-0.5.1-cp27-cp27mu-manylinux1_i686.whl
Algorithm Hash digest
SHA256 718ca286ea67861ebe82367b5f0106ea8c00877f5aefcfe9c2acc505d16ea062
MD5 ae4bc95ded080035e69d9806fc62fcc4
BLAKE2b-256 f793ad1fa9e977da3a9146b6ba014495abe14c5eea30e6265ffa6f2060e8134d

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for msgpack-0.5.1-cp27-cp27m-win_amd64.whl
Algorithm Hash digest
SHA256 82581e634e18e143d7838b5d64b640e7de210a65d216f41c56cc51e65a43781a
MD5 bce49f0e0174c5799c9588855a552980
BLAKE2b-256 304a13a96909ac9654fbcc05828da1ca64db9c3da06748e2bf7e2c2774f08e44

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for msgpack-0.5.1-cp27-cp27m-win32.whl
Algorithm Hash digest
SHA256 388d7fb88dc968ada81e8f05d851cb3c8ae4fce344751e3cdc93dc2f127bdbd1
MD5 1375cd4aa792f6f6e1eb491d6b447ca4
BLAKE2b-256 f9551f3dd2d1e9d4f0ae6a5386a6ec59bf18b5a5c16da160d968c5067796152a

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for msgpack-0.5.1-cp27-cp27m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 6e97a9bdf3b0fa676910411fe8f10a0e3b8b92335640c7a131f1bbcfe1edd7d1
MD5 d77d9593d2cf94372de85b76847fbd2c
BLAKE2b-256 02c87f9533ba1f4876a457504504888c5ba43fc43f2887841816e60a1796e55c

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for msgpack-0.5.1-cp27-cp27m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 95b5dd99fb366d2ca87251d9f755c26b7c3995a1ab86de97546d273016d0042d
MD5 d81e5caa76cf4d2964ed49a7f17fd2b0
BLAKE2b-256 8770c777e7992ac3b7f1a1bb170f65fd094c3e53b47d7bfa3e875be800840507

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