Skip to content

Memo on Python and numpy `dtype`

Romain Hugonnet edited this page Aug 8, 2022 · 1 revision

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))