[plum.structure] Tutorial: Instantiating Structures

This tutorial shows the two methods to create structure instances, unpacking and direct instantiation.

Unpacking

The unpack() utility returns an instance of a structure when provided a plum structure type:

>>> from plum import unpack
>>> from plum.structure import Member, Structure
>>> from plum.int.little import UInt8, UInt16, UInt32
>>>
>>> class MyStruct(Structure):
...     m1: int = Member(cls=UInt8)
...     m2: int = Member(cls=UInt16, default=2)
...     m3: int = Member(cls=UInt32, default=3)
...
>>> unpack(MyStruct, b'\x01\x02\x00\x03\x00\x00\x00')
MyStruct(m1=1, m2=2, m3=3)

Direct Instantiation

plum structure types instantiate directly and accept member values as either positional or keyword arguments.

>>> from plum import unpack
>>> from plum.structure import Member, Structure
>>> from plum.int.little import UInt8, UInt16, UInt32
>>>
>>> class MyStruct(Structure):
...     m1: int = Member(cls=UInt8)
...     m2: int = Member(cls=UInt16, default=2)
...     m3: int = Member(cls=UInt32, default=3)
...
>>> # positional args
>>> MyStruct(1)  # unspecified members default
MyStruct(m1=1, m2=2, m3=3)
>>>
>>> # keyword args only
>>> MyStruct(m1=1)  # unspecified members default
MyStruct(m1=1, m2=2, m3=3)
>>>
>>> # combination
>>> MyStruct(1, m2=0, m3=0)
MyStruct(m1=1, m2=0, m3=0)