[plum.structure] Tutorial: Packing StructuresΒΆ
This tutorial shows the variations of how to pack structure member values into a bytes buffer.
The first way to pack a structure requires instantiating the structure
type and calling the pack()
method:
>>> from plum.structure import Member, Structure
>>> from plum.int.little import UInt8, UInt16
>>>
>>> class MyStruct(Structure):
... m1: int = Member(cls=UInt8)
... m2: int = Member(cls=UInt16, default=2)
...
>>> MyStruct(m1=1, m2=2).pack()
bytearray(b'\x01\x02\x00')
Alternatively, pass the structure type as the first argument and the value
of the structure (in list
, tuple
, or dict
form)
as the second argument. Members with a default value defined in the
structure type may be left unspecified:
>>> from plum import pack >>> >>> # dict mapping >>> pack(MyStruct, {'m1': 1}) # unspecified members default bytearray(b'\x01\x02\x00') >>> >>> # list >>> pack(MyStruct, [1, 0]) bytearray(b'\x01\x00\x00') >>> >>> # tuple >>> pack(MyStruct, (1, 0)) bytearray(b'\x01\x00\x00')Tip
These alternatives may yield slightly faster performance since it avoids instantiating the structure type.