[plum] Tutorial: Determining SizeΒΆ
This tutorial demonstrates the use of the nbytes
property to acquire
the size of a transform instance, a data store, or an instance of a data store.
All data store and transform classes offer a nbytes
property to disclose
the number of bytes a construct produces when packed (or the number of bytes
required to unpack a construct):
>>> from plum.array import ArrayX
>>> from plum.bigendian import uint8, uint16
>>> from plum.structure import Structure, member
>>> from plum.utilities import pack
>>>
>>> fixed_array = ArrayX(fmt=uint16, dims=(3,))
>>> fixed_array.nbytes
6
>>>
>>> class FixedStruct(Structure):
... m1: int = member(fmt=uint8)
... m2: int = member(fmt=uint16)
...
>>> FixedStruct.nbytes
3
When the transform or data store are variably sized, the property raises a
SizeError
:
>>> from typing import List
>>>
>>> greedy_array = ArrayX(fmt=uint16)
>>> greedy_array.nbytes
Traceback (most recent call last):
...
plum.exceptions.SizeError: <transform 'List[int]'> sizes vary
>>>
>>> class GreedyStruct(Structure):
... m1: int = member(fmt=uint8)
... m2: List[int] = member(fmt=greedy_array)
...
>>> GreedyStruct.nbytes
Traceback (most recent call last):
...
plum.exceptions.SizeError: 'GreedyStruct' instance sizes vary
For transforms, the size may be determined by using the len()
function
on the packed bytes for a particular value:
>>> len(greedy_array.pack([1, 2, 3]))
6
When applied to a data store instance, the nbytes
property reveals the size based on the
instance data:
>>> GreedyStruct(m1=1, m2=[1, 2, 3]).nbytes
7