Skip to content

msgpack_streamer

MessagePack streaming reader for line-delimited records.

This module provides :class:MsgPackStreamer which reads MessagePack-encoded records from a file or stream, with optional column renaming. It yields each decoded record as a dictionary, supporting iteration over large files without loading everything into memory.

Example
import os
import tempfile

import msgpack

import py_misc_utils.fs_utils as fsu
import py_misc_utils.msgpack_streamer as ms


tdir = tempfile.mkdtemp()
path = os.path.join(tdir, 'recs.msgpack')
fsu.write_content(path, b''.join(msgpack.packb(r) for r in [{'a': 1}, {'a': 2}]))

recs = list(ms.MsgPackStreamer(path))
assert recs == [{'a': 1}, {'a': 2}], recs

MsgPackStreamer

Stream MessagePack-encoded records from a file or URL.

Example
import os
import tempfile

import msgpack

import py_misc_utils.fs_utils as fsu
import py_misc_utils.msgpack_streamer as ms


tdir = tempfile.mkdtemp()
path = os.path.join(tdir, 'recs.msgpack')
fsu.write_content(path, b''.join(msgpack.packb(r) for r in
                                 [{'old': 1}, {'old': 2}]))

recs = list(ms.MsgPackStreamer(path, rename_columns={'old': 'new'}))
assert recs == [{'new': 1}, {'new': 2}], recs
Source code in py_misc_utils/msgpack_streamer.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
class MsgPackStreamer:
  """Stream MessagePack-encoded records from a file or URL.

  Example:
    import os
    import tempfile

    import msgpack

    import py_misc_utils.fs_utils as fsu
    import py_misc_utils.msgpack_streamer as ms


    tdir = tempfile.mkdtemp()
    path = os.path.join(tdir, 'recs.msgpack')
    fsu.write_content(path, b''.join(msgpack.packb(r) for r in
                                     [{'old': 1}, {'old': 2}]))

    recs = list(ms.MsgPackStreamer(path, rename_columns={'old': 'new'}))
    assert recs == [{'new': 1}, {'new': 2}], recs
  """

  def __init__(self, url, rename_columns=None, **kwargs):
    """Initialize the streamer with a source URL and optional column renaming.

    Args:
      url: The file path or URL to read MessagePack records from.
      rename_columns: Optional mapping of old column names to new column names.
      **kwargs: Additional keyword arguments passed to gfs.open.
    """
    self._url = url
    self._rename_columns = ut.value_or(rename_columns, dict())
    self._kwargs = kwargs

  def generate(self):
    """Yield decoded MessagePack records from the source stream.

    Each record is yielded as a dictionary with renamed columns applied
    according to the _rename_columns mapping.

    Yields:
      Decoded record dictionaries from the MessagePack stream.
    """
    with gfs.open(self._url, mode='rb', **self._kwargs) as stream:
      unpacker = msgpack.Unpacker(stream)
      for recd in unpacker:
        for key, name in self._rename_columns.items():
          recd[name] = recd.pop(key)

        yield recd

  def __iter__(self):
    """Return an iterator over the unpacked records of the stream."""
    return self.generate()

generate()

Yield decoded MessagePack records from the source stream.

Each record is yielded as a dictionary with renamed columns applied according to the _rename_columns mapping.

Yields:

Type Description

Decoded record dictionaries from the MessagePack stream.

Source code in py_misc_utils/msgpack_streamer.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
def generate(self):
  """Yield decoded MessagePack records from the source stream.

  Each record is yielded as a dictionary with renamed columns applied
  according to the _rename_columns mapping.

  Yields:
    Decoded record dictionaries from the MessagePack stream.
  """
  with gfs.open(self._url, mode='rb', **self._kwargs) as stream:
    unpacker = msgpack.Unpacker(stream)
    for recd in unpacker:
      for key, name in self._rename_columns.items():
        recd[name] = recd.pop(key)

      yield recd