[plum] Tutorial: Structure Member Protocol

This tutorial describes the protocol plum Structure types follow during instantiation, pack, and unpack operations. The protocol facilitates defining new plum types which when used as a Structure member type, offer dynamic behavior such as that shown in the Sized Arrays tutorial.


The plum type protocol defines the __unpack__() method as follows:

def __unpack__(cls, buffer, offset, parent, dump):
    return <cls instance>, <new offset>

The unpack() function calls __unpack__() passing the bytes-like buffer and passes either None or a Dump instance for the dump argument (the “and dump” version of unpack passes an instance or if the operation is repeated because of an exception an instance is passed to regenerate the exception with a bytes summary dump). For parent, unpack() passes None as do certain other composition types such as Array when they in turn call the __unpack__() method of their subelements.

Structure types call the __unpack__() method and pass the structure instance as the parent. This allows unpacking logic to inspect previously unpacked structure members.