msgpack-types
msgpack-types is a Python library that provides type stubs for the popular 'msgpack' serialization library. Its purpose is to enable static type checking and enhance developer tooling like autocompletion for code that interacts with MessagePack data. The current version is 0.7.0, and it is actively maintained with frequent releases, often in sync with or following updates to the core `msgpack` library.
Warnings
- gotcha When unpacking, the `raw` parameter in `msgpack.unpackb` (and `Unpacker`) determines whether 'str' (raw) types in MessagePack are decoded to Python `bytes` (`raw=True`) or `str` (Unicode, `raw=False`). The default for `msgpack>=1.0` is `raw=False`, assuming UTF-8. Be explicit to avoid encoding/decoding issues.
- breaking The `encoding` option for `msgpack.Packer` and `msgpack.Unpacker` was removed in `msgpack 1.0`. UTF-8 is now always used for string encoding and decoding when `raw=False`.
- gotcha Type stubs only provide static analysis; they do not alter runtime behavior. Installing `msgpack-types` without `msgpack` will not provide MessagePack serialization functionality at runtime, only type hints during development.
- gotcha Prior to `msgpack 1.0`, `use_bin_type=True` was not the default for `Packer`, meaning `bytes` objects might have been encoded as 'raw' types instead of the 'bin' type specified in MessagePack spec 2.0. This can lead to compatibility issues with newer decoders.
- gotcha The `strict_map_key` option in `msgpack.Unpacker` defaults to `True` in `msgpack 1.0` to mitigate hash DoS attacks. If your MessagePack data contains map keys that are not `bytes` or `str` (e.g., integers as keys), unpacking will fail unless `strict_map_key=False` is set.
Install
-
pip install msgpack-types -
pip install msgpack
Imports
- packb
import msgpack packed_data = msgpack.packb(...)
- unpackb
import msgpack unpacked_data = msgpack.unpackb(...)
Quickstart
import msgpack
def process_data(data: dict) -> bytes:
packed = msgpack.packb(data, use_bin_type=True)
return packed
def decode_data(packed_data: bytes) -> dict:
# raw=False decodes binary strings to Python str (UTF-8 assumed)
unpacked = msgpack.unpackb(packed_data, raw=False)
return unpacked # type: ignore
my_data = {'name': 'Alice', 'age': 30, 'cities': ['New York', 'London']}
# Using the functions with type hints
encoded = process_data(my_data)
decoded = decode_data(encoded)
print(f"Original: {my_data}")
print(f"Encoded: {encoded}")
print(f"Decoded: {decrypted}")
# Example of type checking with MyPy (after installing msgpack-types):
# If you were to do `process_data('not a dict')`, MyPy would flag a type error.