ivan_pozdeev ivan_pozdeev - 1 month ago 6
Python Question

Get information about a numpy dtype

I'm trying to implement a validity check on a numpy type - specifically, if

np.longdouble
is the 80-bit extended precision float - and get its raw byte size (with padding).

Accoring to
dtype
docs
, I can get a whole bunch of information from attributes. But, whichever attribute I check, I get

In [23]: np.longdouble.nbytes
Out[23]: <attribute 'nbytes' of 'numpy.generic' objects>


instead of the number.

I can get a whole bunch of information from
np.finfo(np.longdouble)
but it doesn't include byte size.

Sure, I can create an array of that type and calculate the size or something... but is this really necessary to get information that's not bound to a specific instance?

Answer

According to Numpy size of data type, np.dtype(<type>) is needed to actually get the real attribute values. Weird!

Here (using the dump module):

In [27]: dump(np.dtype(np.longdouble))
alignment : 8
base : float64
byteorder : =
char : g
descr : [('', '<f8')]
fields : None
flags : 0
hasobject : False
isalignedstruct : False
isbuiltin : 1
isnative : True
itemsize : 8
kind : f
metadata : None
name : float64
names : None
num : 13
shape : ()
str : <f8
subdtype : None
type : <type 'numpy.float64'>

This output is from Python 2.7 on win32 platform and, predictably, np.longdouble is double rather than extended precision here.

For comparison, here's an output from x86 CentOS 6 where it's extended:

alignment : 4
base : float96
byteorder : =
char : g
descr : [('', '<f12')]
fields : None
flags : 0
hasobject : False
isbuiltin : 1
isnative : True
itemsize : 12
kind : f
metadata : None
name : float96
names : None
num : 13
shape : ()
str : <f12
subdtype : None
type : <type 'numpy.float96'>