u-msgpack-python
u-msgpack-python is a lightweight MessagePack serializer and deserializer module written entirely in pure Python. It is compatible with both Python 2 and 3, as well as CPython and PyPy implementations, and fully complies with the latest MessagePack specification, including support for binary, UTF-8 string, application-defined ext, and timestamp types. The current version is 2.8.0, with releases occurring a few times per year to maintain compliance and add features.
Warnings
- gotcha Confusing `u-msgpack-python` with the `msgpack` library (the CPython binding with fallback). While both handle MessagePack, `u-msgpack-python` is a pure Python implementation and may have subtle behavioral or performance differences. The `msgpack` library (on PyPI as `msgpack`) had significant breaking changes in its 1.0 release regarding Python 2 support, default binary/string handling, and removed encoding options. Users should be aware of which library they are using.
- gotcha Handling old MessagePack specification data. By default, `u-msgpack-python` is fully compliant with the latest MessagePack specification, which distinguishes between string and binary types. Older specifications used a single 'raw' type. If interacting with systems that generate old-spec MessagePack, you might need to enable `umsgpack.compatibility = True` or use specific packing/unpacking options.
- gotcha Loss of float precision during serialization. The `packb` and `pack` functions offer a `force_float_precision` option ('single' or 'double'). Using 'single' will force floats to be packed as IEEE-754 single-precision, which may result in a loss of precision if the original float was double-precision.
Install
-
pip install u-msgpack-python
Imports
- umsgpack
import umsgpack
Quickstart
import umsgpack
data = {"name": "Alice", "age": 30, "is_student": False}
# Serialize a Python object to MessagePack bytes
packed_data = umsgpack.packb(data)
print(f"Packed data: {packed_data}")
# Deserialize MessagePack bytes back to a Python object
unpacked_data = umsgpack.unpackb(packed_data)
print(f"Unpacked data: {unpacked_data}")
# Example with streaming to/from a file-like object
from io import BytesIO
f = BytesIO()
umsgpack.pack({"compact": True, "schema": 0}, f)
umsgpack.pack([1, 2, 3], f)
f.seek(0)
# Unpack multiple objects from the stream
obj1 = umsgpack.unpack(f)
obj2 = umsgpack.unpack(f)
print(f"Object 1 from stream: {obj1}")
print(f"Object 2 from stream: {obj2}")