Msgpack-NumPy

0.4.8 · active · verified Sun Apr 12

This package provides encoding and decoding routines that enable the serialization and deserialization of numerical and array data types from NumPy using the highly efficient MessagePack format. It also supports serialization of Python's native complex data types. The current version is 0.4.8, and it maintains compatibility with Python versions 2.7 and 3.5+.

Warnings

Install

Imports

Quickstart

The quickest way to use msgpack-numpy is to call `m.patch()` after importing `msgpack` and `msgpack_numpy`. This automatically configures `msgpack.packb` and `msgpack.unpackb` to handle NumPy data types. It's crucial to use `use_bin_type=True` during packing for binary data and `raw=False` (default) for unpacking strings.

import msgpack
import msgpack_numpy as m
import numpy as np

# Easiest way: Monkey-patch msgpack to be numpy-aware
m.patch()

# Example NumPy array
data = {'array': np.array([1.2, 3.4, 5.6], dtype=np.float32), 'scalar': np.float64(7.8)}

# Serialize
packed_data = msgpack.packb(data, use_bin_type=True)
print(f"Packed size: {len(packed_data)} bytes")

# Deserialize
unpacked_data = msgpack.unpackb(packed_data, raw=False)

# Verify
print(f"Original array type: {type(data['array'])}, dtype: {data['array'].dtype}")
print(f"Unpacked array type: {type(unpacked_data[b'array'])}, dtype: {unpacked_data[b'array'].dtype}")
print(f"Original scalar type: {type(data['scalar'])}, value: {data['scalar']}")
print(f"Unpacked scalar type: {type(unpacked_data[b'scalar'])}, value: {unpacked_data[b'scalar']}")

# Ensure unpacked arrays are modifiable if needed (they are read-only by default)
original_array = unpacked_data[b'array'].copy()
original_array[0] = 99.9
print(f"Modified array: {original_array}")

view raw JSON →