[plum] Tutorial: Determining Size¶
This tutorial demonstrates the use of the nbytes
property to determine
the size of a plum
type or instances of a plum
type.
Instance Property¶
All instances of plum
types offer a nbytes
property which indicates
the number of bytes the instance yields when it is packed. The following
example demonstrates using a dimensioned array type. Since the array
element size is 2 and the array dimension is 3, the total number of
bytes when packed is the product of the two, 6:
>>> from plum.array import Array
>>> from plum.int.big import UInt16
>>>
>>> class Array16(Array, dims=(3,), item_cls=UInt16):
... """Fixed size array."""
...
>>> array = Array16([1, 2, 3])
>>> array.nbytes
6
Class Property¶
All plum
type classes offer the same nbytes
property. When the plum
type is a fixed size, the property indicates the total number of bytes
yielded when packed (regardless of data packed). The following example
demonstrates using the dimensioned array from the last section:
>>> Array16.nbytes
6
When the plum
type is variable in size (when the number of bytes packed
is determined by the data being packed), use of this property raises
an plum.SizeError
exception:
>>> class GreedyArray(Array, item_cls=UInt16):
... """Variable sized array (no dimensions)."""
...
>>> GreedyArray.nbytes
Traceback (most recent call last):
...
plum._exceptions.SizeError: 'GreedyArray' instance sizes vary
Instead, the nbytes
properties must be used on an instance of that
variably sized type:
>>> array = GreedyArray([1, 2, 3])
>>> array.nbytes
6