-
Notifications
You must be signed in to change notification settings - Fork 41
Memo on Python and numpy `dtype`
When checking for data types, it's good to keep in mind that there are both python.numbers
and numpy
data types that are widely used. To our knowledge, there is no dtype
objects that covers both simultaneously. This can result in a lot of errors when checking for data inputs...
For python.numbers
, the structure is described here: https://docs.python.org/3/reference/datamodel.html
For numpy
, here: https://numpy.org/doc/stable/reference/arrays.scalars.html
Some simple tests to understand this:
# For integers
isinstance(1, np.integer)
False
isinstance(np.int16(1), np.integer)
True
isinstance(np.int16(1), int)
False
isinstance(1, int)
True
# For floats
isinstance(np.float16(1.5), np.floating)
True
isinstance(1.5, np.floating)
False
isinstance(np.float16(1.5), float)
False
isinstance(1.5, float)
True
Careful also, as there is something confusing in the naming of dtypes
: np.float
is just a (now deprecated) alias for float
and np.int
for int
. The correct types for numpy are np.floating
and np.integer
.
Therefore, to test non-complex numeric numbers, we use throughout the package:
isinstance(x, (float, np.floating, int, np.integer))