[plum.items] Tutorial: Item Collections

This tutorial shows how to create typed item collections for packing bytes. This alleviates the need for creating custom Structure subclasses in applications where data structure varies.

An example situation which shows the benefit is when passing message data to a communications driver. Passing a Items instance facilitates logging the message showing the individual item values.

>>> from plum.int.little import UInt8
>>> from plum.items import Items
>>>
>>> def send_message(message):
...     msg, dump = message.pack_and_dump()
...     print(dump)
...     transmit(msg)
...
>>> message = Items([
...   UInt8(1), # command
...   UInt8(2), # subcommand
... ])
>>> send_message(message)
+--------+--------+-------+-------+-------+
| Offset | Access | Value | Bytes | Type  |
+--------+--------+-------+-------+-------+
|        |        |       |       | Items |
| 0      | [0]    | 1     | 01    | UInt8 |
| 1      | [1]    | 2     | 02    | UInt8 |
+--------+--------+-------+-------+-------+

The Items class subclasses Python’s built-in list and inherits all of the behaviors and features. The alternative NamedItems shares the same purpose but subclasses Python’s built-in dict. Using NamedItems facilitates meaningful names within the log for each item in the collection. For example:

>>> from plum.items import NamedItems
>>>
>>> message = NamedItems(command=UInt8(1), subcommand=UInt8(2))
>>> send_message(message)
+--------+-------------------+-------+-------+------------+
| Offset | Access            | Value | Bytes | Type       |
+--------+-------------------+-------+-------+------------+
|        |                   |       |       | NamedItems |
| 0      | [0] (.command)    | 1     | 01    | UInt8      |
| 1      | [1] (.subcommand) | 2     | 02    | UInt8      |
+--------+-------------------+-------+-------+------------+

The NamedItems inherits dict behaviors but also supports retrieving the item by its name as an attribute. For example:

>>> message.command
UInt8(1)

Important

Values provided to either Items or NamedItems must be plum type instances otherwise the packing operation raises a PackingError.