msgpack – Pack object in msgpack format — Adafruit CircuitPython 1 documentation (original) (raw)

The msgpack format is similar to json, except that the encoded data is binary. See https://msgpack.org for details. The module implements a subset of the cpython module msgpack-python.

Not implemented: 64-bit int, uint, float.

For more information about working with msgpack, see the CPython Library Documentation.

Example 1:

import msgpack from io import BytesIO

b = BytesIO() msgpack.pack({'list': [True, False, None, 1, 3.14], 'str': 'blah'}, b) b.seek(0) print(msgpack.unpack(b))

Example 2: handling objects:

from msgpack import pack, unpack, ExtType from io import BytesIO

class MyClass: def init(self, val): self.value = val def str(self): return str(self.value)

data = MyClass(b'my_value')

def encoder(obj): if isinstance(obj, MyClass): return ExtType(1, obj.value) return f"no encoder for {obj}"

def decoder(code, data): if code == 1: return MyClass(data) return f"no decoder for type {code}"

buffer = BytesIO() pack(data, buffer, default=encoder) buffer.seek(0) decoded = unpack(buffer, ext_hook=decoder) print(f"{data} -> {buffer.getvalue()} -> {decoded}")

Available on these boards

msgpack.pack(obj: object, stream: circuitpython_typing.ByteStream, *, default: Callable[[object], None] | None = None) → None

Output object to stream in msgpack format.

Parameters:

msgpack.unpack(stream: circuitpython_typing.ByteStream, *, ext_hook: Callable[[int, bytes], object] | None = None, use_list: bool = True) → object

Unpack and return one object from stream.

Parameters:

Return object:

object read from stream.

class msgpack.ExtType(code: int, data: bytes)

ExtType represents ext type in msgpack.

Constructor :param int code: type code in range 0~127. :param bytes data: representation.

code_: int_

The type code, in range 0~127.

data_: bytes_

Data.