UsageΒΆ
ormsgpack provides the ormsgpack.packb() and ormsgpack.unpackb()
functions to serialize and deserialize a Python object to and from MessagePack format,
respectively. This is an example of serializing and deserializing an object:
>>> import ormsgpack, datetime, numpy
>>> event = {
... "type": "put",
... "time": datetime.datetime(1970, 1, 1),
... "uid": 1,
... "data": numpy.array([1, 2]),
... }
>>> ormsgpack.packb(event, option=ormsgpack.OPT_SERIALIZE_NUMPY)
b'\x84\xa4type\xa3put\xa4time\xb31970-01-01T00:00:00\xa3uid\x01\xa4data\x92\x01\x02'
>>> ormsgpack.unpackb(_)
{'type': 'put', 'time': '1970-01-01T00:00:00', 'uid': 1, 'data': [1, 2]}
The option argument of ormsgpack.packb() and ormsgpack.unpackb()
can be used to modify their behavior, by specifying one or more options. Options are
integers and can be combined using the bitwise OR operator, e.g.,
ormsgpack.OPT_DATETIME_AS_TIMESTAMP_EXT | ormsgpack.OPT_NON_STR_KEYS. The above
example uses the ormsgpack.OPT_SERIALIZE_NUMPY option to enable the
serialization of numpy types.
By default, ormsgpack only accepts dict objects with string keys. The
ormsgpack.OPT_NON_STR_KEYS option can be used to serialize and deserialize
dict objects with keys of other types:
>>> import ormsgpack
>>>
>>> ormsgpack.packb(
... {0: [1, 2], 1.0: [3, 4]},
... )
TypeError: Dict key must be str
>>> ormsgpack.packb(
... {0: [1, 2], 1.0: [3, 4]},
... option=ormsgpack.OPT_NON_STR_KEYS,
... )
b'\x82\x00\x92\x01\x02\xcb?\xf0\x00\x00\x00\x00\x00\x00\x92\x03\x04'
>>> ormsgpack.unpackb(_, option=ormsgpack.OPT_NON_STR_KEYS)
{0: [1, 2], 1.0: [3, 4]}
Be aware that, when using this option, a serialized map may contain elements with the
same key, as different dict keys may be serialized to the same object. In
such a case, a MessagePack deserializer will presumably keep only one element for any
given key, as is the case for ormsgpack.unpackb():
>>> import ormsgpack, enum
>>> class Action(enum.Enum):
... ALLOW = 1
... DENY = 2
...
>>> ormsgpack.packb(
... {
... Action.ALLOW: [443, 993],
... 1: [80, 143],
... },
... option=ormsgpack.OPT_NON_STR_KEYS,
... )
b'\x82\x01\x92\xcd\x01\xbb\xcd\x03\xe1\x01\x92P\xcc\x8f'
>>> ormsgpack.unpackb(_, option=ormsgpack.OPT_NON_STR_KEYS)
{1: [80, 143]}
ormsgpack supports various types natively, including dataclasses and Pydantic models.
The default argument of ormsgpack.packb() can be used to handle objects
that are not natively serializable:
>>> import ormsgpack, decimal
>>> def default(obj):
... if isinstance(obj, decimal.Decimal):
... return ormsgpack.Ext(0, str(obj).encode())
... raise TypeError
...
>>> ormsgpack.packb(decimal.Decimal("3.14"))
TypeError: Type is not msgpack serializable: decimal.Decimal
>>> ormsgpack.packb(decimal.Decimal("3.14"), default=default)
b'\xd6\x003.14'
>>> ormsgpack.packb({1, 2}, default=default)
TypeError: Type is not msgpack serializable: set
ormsgpack provides the ormsgpack.Ext type to serialize objects as
MessagePack extension types. The ext_hook argument of ormsgpack.unpackb()
can be used to deserialize extension types:
>>> import ormsgpack, decimal
>>> def ext_hook(tag, data):
... if tag == 0:
... return decimal.Decimal(data.decode())
... raise TypeError
...
>>> ormsgpack.packb(ormsgpack.Ext(0, str(decimal.Decimal("3.14")).encode()))
b'\xd6\x003.14'
>>> ormsgpack.unpackb(_, ext_hook=ext_hook)
Decimal('3.14')
If an object is not handled, default and ext_hook should raise an exception.
Otherwise, the object is serialized or deserialized as None, because of Python
implicit call return value:
>>> import ormsgpack, decimal
>>> def default(obj):
... if isinstance(obj, decimal.Decimal):
... return ormsgpack.Ext(0, str(obj).encode())
...
>>> ormsgpack.packb({1, 2}, default=default)
b'\xc0'
>>> print(ormsgpack.unpackb(_))
None
default can also be used to serialize some supported types to a custom format by
enabling the corresponding passthrough options, e.g.:
>>> import ormsgpack, uuid
>>> def default(obj):
... if isinstance(obj, uuid.UUID):
... return ormsgpack.Ext(0, obj.bytes)
... raise TypeError
...
>>> ormsgpack.packb(
... uuid.UUID("886313e1-3b8a-5372-9b90-0c9aee199e5d"),
... )
b'\xd9$886313e1-3b8a-5372-9b90-0c9aee199e5d'
>>> ormsgpack.packb(
... uuid.UUID("886313e1-3b8a-5372-9b90-0c9aee199e5d"),
... option=ormsgpack.OPT_PASSTHROUGH_UUID,
... )
TypeError: Type is not msgpack serializable: UUID
>>> ormsgpack.packb(
... uuid.UUID("886313e1-3b8a-5372-9b90-0c9aee199e5d"),
... option=ormsgpack.OPT_PASSTHROUGH_UUID,
... default=default,
... )
b'\xd8\x00\x88c\x13\xe1;\x8aSr\x9b\x90\x0c\x9a\xee\x19\x9e]'
See the API Reference and Types sections for more details.