[Numpy-discussion] correct sizeof for ndarray

Allan Haldane allanhaldane at gmail.com
Tue Oct 20 09:56:02 EDT 2015

On 10/20/2015 12:05 AM, Jason Newton wrote:
> Hi folks,
> I noticed an unexpected behavior of itemsize for structures with offsets
> that are larger than that of a packed structure in memory.  This matters
> when parsing in memory structures from C and some others (recently and
> HDF5/h5py detail got me for a bit).
> So what is the correct way to get "sizeof" a structure?  AFAIK this is
> the size of the last item + it's offset.  If this doesn't exist...
> shouldn't it?
> Thanks,
> Jason

Hi Jason,

The 'itemsize' attribute of a dtype object is probably what you're 
looking for. It gives the itemsize in bytes.

"last item + it's offset" is not a reliable way to get the itemsize 
because "aligned" (and other) structures can have trailing padding, just 
like C structs:

     >>> dtype('i4,u1', align=True).itemsize

The documentation on all this is a little scattered right now, but there 
are hints in the array.dtypes reference page and the dtype docstring.


More information about the NumPy-Discussion mailing list