Skip to main content

MessagePack (de)serializer.

Project description

MessagePack for Python

Build Status Documentation Status

What's this

MessagePack <https://msgpack.org/>_ 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.

Compatibility with the old format

You can use use_bin_type=False option to pack bytes object into raw type in the old msgpack spec, instead of bin type in new msgpack spec.

You can unpack old msgpack format using raw=True option. It unpacks str (raw) type in msgpack into Python bytes.

See note below for detail.

Major breaking changes in msgpack 1.0

  • Python 2

    • The extension module does not support Python 2 anymore. The pure Python implementation (msgpack.fallback) is used for Python 2.
  • Packer

    • use_bin_type=True by default. bytes are encoded in bin type in msgpack. If you are still sing Python 2, you must use unicode for all string types. You can use use_bin_type=False to encode into old msgpack format.
    • encoding option is removed. UTF-8 is used always.
  • Unpacker

    • raw=False by default. It assumes str types are valid UTF-8 string and decode them to Python str (unicode) object.
    • encdoding option is rmeoved. You can use raw=True to support old format.
    • Default value of max_buffer_size is changed from 0 to 100 MiB.
    • Default value of strict_map_key is changed to True to avoid hashdos. You need to pass strict_map_key=False if you have data which contain map keys which type is not bytes or str.

Install

$ pip install msgpack

Pure Python implementation

The extension module in msgpack (msgpack._cmsgpack) does not support Python 2 and PyPy.

But msgpack provides a pure Python implementation (msgpack.fallback) for PyPy and Python 2.

Since the pip uses the pure Python implementation, Python 2 support will not be dropped in the foreseeable future.

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.

How to use

NOTE: In examples below, I use raw=False and use_bin_type=True for users using msgpack < 1.0. These options are default from msgpack 1.0 so you can omit them.

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(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. The type for representing both string and binary types was named raw.

You can pack into and unpack from this old spec using use_bin_type=False and raw=True options.

    >>> import msgpack
    >>> msgpack.unpackb(msgpack.packb([b'spam', u'eggs'], use_bin_type=False), raw=True)
    [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.

Security

To unpacking data received from unreliable source, msgpack provides two security options.

max_buffer_size (default: 10010241024) limits the internal buffer size. It is used to limit the preallocated list size too.

strict_map_key (default: True) limits the type of map keys to bytes and str. While msgpack spec doesn't limit the types of the map keys, there is a risk of the hashdos. If you need to support other types for map keys, use strict_map_key=False.

Performance tips

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

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.

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-1.0.0rc1.tar.gz (122.8 kB view details)

Uploaded Source

Built Distributions

msgpack-1.0.0rc1-cp38-cp38-manylinux1_x86_64.whl (261.6 kB view details)

Uploaded CPython 3.8

msgpack-1.0.0rc1-cp38-cp38-manylinux1_i686.whl (248.3 kB view details)

Uploaded CPython 3.8

msgpack-1.0.0rc1-cp37-cp37m-manylinux1_x86_64.whl (250.3 kB view details)

Uploaded CPython 3.7m

msgpack-1.0.0rc1-cp37-cp37m-manylinux1_i686.whl (237.3 kB view details)

Uploaded CPython 3.7m

msgpack-1.0.0rc1-cp36-cp36m-manylinux1_x86_64.whl (252.9 kB view details)

Uploaded CPython 3.6m

msgpack-1.0.0rc1-cp36-cp36m-manylinux1_i686.whl (237.5 kB view details)

Uploaded CPython 3.6m

msgpack-1.0.0rc1-cp35-cp35m-manylinux1_x86_64.whl (246.8 kB view details)

Uploaded CPython 3.5m

msgpack-1.0.0rc1-cp35-cp35m-manylinux1_i686.whl (232.8 kB view details)

Uploaded CPython 3.5m

File details

Details for the file msgpack-1.0.0rc1.tar.gz.

File metadata

  • Download URL: msgpack-1.0.0rc1.tar.gz
  • Upload date:
  • Size: 122.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.40.2 CPython/3.8.0

File hashes

Hashes for msgpack-1.0.0rc1.tar.gz
Algorithm Hash digest
SHA256 a5c8bb6967d838a0f0ad689b09f54c75230f877a3b240001663a970a12c976b2
MD5 3de3d27348e037d07ea87651e50da8ab
BLAKE2b-256 fbc343aa29d8229d47a4e2976f197a1ad5c53860ca02eb5c64ab31db8f905e63

See more details on using hashes here.

File details

Details for the file msgpack-1.0.0rc1-cp38-cp38-manylinux1_x86_64.whl.

File metadata

  • Download URL: msgpack-1.0.0rc1-cp38-cp38-manylinux1_x86_64.whl
  • Upload date:
  • Size: 261.6 kB
  • Tags: CPython 3.8
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.40.2 CPython/3.8.0

File hashes

Hashes for msgpack-1.0.0rc1-cp38-cp38-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 bc17fccdf8f1bc61cfca1ef8de549ce52f6f78a9c99b948d7c822595f8288a5a
MD5 c8a35d8c1211e33455a90f3ddef9f955
BLAKE2b-256 a90f6afb8aab1e46c9b468caed4ea216984c767ae6bc4f573607089ee9328b55

See more details on using hashes here.

File details

Details for the file msgpack-1.0.0rc1-cp38-cp38-manylinux1_i686.whl.

File metadata

  • Download URL: msgpack-1.0.0rc1-cp38-cp38-manylinux1_i686.whl
  • Upload date:
  • Size: 248.3 kB
  • Tags: CPython 3.8
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.40.2 CPython/3.8.0

File hashes

Hashes for msgpack-1.0.0rc1-cp38-cp38-manylinux1_i686.whl
Algorithm Hash digest
SHA256 ae65c7060c7d08aca19cac8fe7650443970478c3ec392daa612d6eb2ee5f77d4
MD5 dc7e73333e9606359ed57588e0e4900c
BLAKE2b-256 c7697848920f260e76cd6461af20f9bff977b6436b34bee128df41df59c2aa25

See more details on using hashes here.

File details

Details for the file msgpack-1.0.0rc1-cp37-cp37m-manylinux1_x86_64.whl.

File metadata

  • Download URL: msgpack-1.0.0rc1-cp37-cp37m-manylinux1_x86_64.whl
  • Upload date:
  • Size: 250.3 kB
  • Tags: CPython 3.7m
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.40.2 CPython/3.8.0

File hashes

Hashes for msgpack-1.0.0rc1-cp37-cp37m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 27d4950bb1ce5ce6f95f8e1c36e789ac44f4c5662d9d8eaac88dae83dfdccd25
MD5 dc17da3c7e51696824b52983b66ffc7a
BLAKE2b-256 34a65d35b0ae69642444981ed8e0fc604bca2cb9ba2ed6bf8034d872d0b22c5f

See more details on using hashes here.

File details

Details for the file msgpack-1.0.0rc1-cp37-cp37m-manylinux1_i686.whl.

File metadata

  • Download URL: msgpack-1.0.0rc1-cp37-cp37m-manylinux1_i686.whl
  • Upload date:
  • Size: 237.3 kB
  • Tags: CPython 3.7m
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.40.2 CPython/3.8.0

File hashes

Hashes for msgpack-1.0.0rc1-cp37-cp37m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 d715bd7e8f6e1488f2ad195719de8af24ab3bf0f394873a4f74579468243d014
MD5 da53799c3f2e843ea84d71c4379037c4
BLAKE2b-256 5d8ab6a7d19934a13d9fe606d225f8268b4cef6bc03c6738aae3a5d6eabf0229

See more details on using hashes here.

File details

Details for the file msgpack-1.0.0rc1-cp36-cp36m-manylinux1_x86_64.whl.

File metadata

  • Download URL: msgpack-1.0.0rc1-cp36-cp36m-manylinux1_x86_64.whl
  • Upload date:
  • Size: 252.9 kB
  • Tags: CPython 3.6m
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.40.2 CPython/3.8.0

File hashes

Hashes for msgpack-1.0.0rc1-cp36-cp36m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 4e1bc8e65425999b3231205d94c7bfc9d9a73c7e1032fccb3d90e77a9d01cc1e
MD5 dbdf64b70efb0aa11e0ae5b9f05c00d1
BLAKE2b-256 4974b8bd629787630352e7c8f38fef0181e915503f52d1b7ad4c826c2d173277

See more details on using hashes here.

File details

Details for the file msgpack-1.0.0rc1-cp36-cp36m-manylinux1_i686.whl.

File metadata

  • Download URL: msgpack-1.0.0rc1-cp36-cp36m-manylinux1_i686.whl
  • Upload date:
  • Size: 237.5 kB
  • Tags: CPython 3.6m
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.40.2 CPython/3.8.0

File hashes

Hashes for msgpack-1.0.0rc1-cp36-cp36m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 d41306262d677d755bde2300ecccbccbe0aec022eb6faea8d8df550f02fb20c4
MD5 e23b52caf72301a67182a306ef280e2a
BLAKE2b-256 3f90515dd8109c68c243bfe686c564b4b4cf512e06047bb32ea0ec57f273991a

See more details on using hashes here.

File details

Details for the file msgpack-1.0.0rc1-cp35-cp35m-manylinux1_x86_64.whl.

File metadata

  • Download URL: msgpack-1.0.0rc1-cp35-cp35m-manylinux1_x86_64.whl
  • Upload date:
  • Size: 246.8 kB
  • Tags: CPython 3.5m
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.40.2 CPython/3.8.0

File hashes

Hashes for msgpack-1.0.0rc1-cp35-cp35m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 ac47b8cef1a5838de5f20e0e44d174d79e4b77b5678252c8fc795bf44bcd6150
MD5 bcb2f3ad595838232c82acb6f5ad69db
BLAKE2b-256 c8f587358836be1b4aba1e47665bf3749436a87911f2531f2143e4b89052db9b

See more details on using hashes here.

File details

Details for the file msgpack-1.0.0rc1-cp35-cp35m-manylinux1_i686.whl.

File metadata

  • Download URL: msgpack-1.0.0rc1-cp35-cp35m-manylinux1_i686.whl
  • Upload date:
  • Size: 232.8 kB
  • Tags: CPython 3.5m
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.40.2 CPython/3.8.0

File hashes

Hashes for msgpack-1.0.0rc1-cp35-cp35m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 315c9d398359d6e41278f7b9882efe0f26ae469ec5d9c85e06a81d0f6c589f1c
MD5 0c4930e98461c7e8e7c3973308f4c568
BLAKE2b-256 86312ddd66f7e8d0c65e14410e49a69f3988d5656515c47813a62c8063364413

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