Streaming

The streaming pack() and unpack() functions allow packing and unpacking objects directly to and from a stream, respectively. Streaming may be necessary when unpacking serialized bytes whose size is unknown in advance, or it may be more convenient and efficient when working directly with stream objects (e.g. files or stream sockets).

Packing

pack(obj, fp) serializes Python object obj to a .write() supporting file-like object fp.

>>> class Foo:
...     def write(self, data):
...         # write 'data' bytes
...         pass
... 
>>> f = Foo()
>>> umsgpack.pack({u"compact": True, u"schema": 0}, f)
>>> 
umsgpack.pack(obj, fp, **options)

Serialize a Python object into MessagePack bytes.

Parameters:
  • obj – a Python object

  • fp – a .write()-supporting file-like object

Keyword Arguments:
  • ext_handlers (dict) – dictionary of Ext handlers, mapping a custom type to a callable that packs an instance of the type into an Ext object

  • force_float_precision (str) – “single” to force packing floats as IEEE-754 single-precision floats, “double” to force packing floats as IEEE-754 double-precision floats

Returns:

None

Raises:

UnsupportedTypeException(PackException) – Object type not supported for packing.

Example

>>> f = open('test.bin', 'wb')
>>> umsgpack.pack({u"compact": True, u"schema": 0}, f)

Also available under the umsgpack.dump() alias.

Unpacking

unpack(fp) deserializes a Python object from a .read() supporting file-like object fp.

>>> class Bar:
...     def read(self, n):
...         # read and return 'n' number of bytes
...         return b"\x01"*n
... 
>>> f = Bar()
>>> umsgpack.unpack(f)
1
>>> 
umsgpack.unpack(fp, **options)

Deserialize MessagePack bytes into a Python object.

Parameters:

fp – a .read()-supporting file-like object

Keyword Arguments:
  • ext_handlers (dict) – dictionary of Ext handlers, mapping integer Ext type to a callable that unpacks an instance of Ext into an object

  • use_ordered_dict (bool) – unpack maps into OrderedDict, instead of dict (default False)

  • use_tuple (bool) – unpacks arrays into tuples, instead of lists (default False)

  • allow_invalid_utf8 (bool) – unpack invalid strings into instances of InvalidString, for access to the bytes (default False)

Returns:

Python object

Raises:

Example

>>> f = open('test.bin', 'rb')
>>> umsgpack.unpackb(f)
{'compact': True, 'schema': 0}

Also available under the umsgpack.load() alias.