Transform dict/iterable values to bytes and vice versa.

[plum.items] Module Reference

The plum.items module provides the ItemsX transform which converts objects as specified by a format into bytes and vice versa. This reference page shows how to create and use an ItemsX transform for packing and unpacking bytes, a lighter weight method than a custom Structure subclass. This page also provides API details.

The examples shown on this page require the following setup:

>>> from plum.array import ArrayX
>>> from plum.littleendian import uint8
>>> from plum.items import ItemsX
>>> from plum.utilities import pack, unpack

Basic Usage

The ItemsX transform accepts the following arguments:

fmt:transform format
name:transform name (for representations including dump format column)

The ItemsX transform fmt argument accepts a transform or any dictionary, list, or tuple of transforms (all the variations described in the Arbitrary Format tutorial).

When packing, the items transform accepts values and converts them into a bytes sequence per the fmt:

>>> fmt = ItemsX(fmt=(uint8, uint8))
>>> buffer = pack([0, 1], fmt)
>>> buffer

When unpacking, the items transform produces values from the bytes sequence per the fmt:

>>> unpack(fmt, buffer)
(0, 1)

But you could just as easily pass [uint8, uint16] as the format into the pack() and unpack() utility methods. Wrapping a format in an ItemsX instance becomes necessary when specifying it as the fmt argument of an ArrayX or Structure member. For example:

>>> fmt = ArrayX(fmt=ItemsX(fmt=(uint8, uint8)), dims=(2,))
>>> buffer = pack([(0, 1), (2, 3)], fmt)
>>> buffer
>>> unpack(fmt, buffer)
[(0, 1), (2, 3)]

API Reference

class plum.items.ItemsX(fmt: Union[Dict[str, Any], List[Any], plum.transform.Transform, Tuple[Any, ...], Type[], None] = None, name: Optional[str] = None, hint: Optional[str] = None)

Value to bytes and bytes to value transformer.


Items format.


Transform format name (for repr and dump “Format” column).


Transform format size in bytes.

pack(value: Any) → bytes

Pack value as formatted bytes.

Raises:PackError if type error, value error, etc.
pack_and_dump(value: Any) → Tuple[bytes, plum.dump.Dump]

Pack value as formatted bytes and produce bytes summary.

Raises:PackError if type error, value error, etc.
unpack(buffer: bytes) → Any

Unpack value from formatted bytes.

Raises:UnpackError if insufficient bytes, excess bytes, or value error
unpack_and_dump(buffer: bytes) → Tuple[Any, plum.dump.Dump]

Unpack value from bytes and produce packed bytes summary.

Raises:UnpackError if insufficient bytes, excess bytes, or value error