8

Many numpy functions take dtype arguments as either strings (like "float64") or numpy datatypes (like numpy.float64) or even python datatypes (like float).

I need to compare two datatypes and want to support this flexible interface. Is there a function under which all of these are forms are equivalent? I.e. I want the minimal function f such that

f("float64") == f(numpy.float64) == f(float)

What does numpy use internally?

2 Answers 2

13

You should read the Scalars page of the numpy documentation, which describes the data type hierarchy.

For comparing dtypes themselves, you can use np.issubdtype. Some examples:

>>> import numpy as np
>>> np.issubdtype(np.int32, int)
True
>>> np.issubdtype(np.int32, float)
False
>>> np.issubdtype(float, np.floating)
True
>>> np.issubdtype(float, np.inexact)
True
>>> np.issubdtype(np.float32, float)
True
>>> np.issubdtype(np.float32, int)
False
>>> np.issubdtype(np.float32, np.floating)
True
Sign up to request clarification or add additional context in comments.

2 Comments

Ah, I didn't think of subdtype comparison. Nice.
Looks preferable to 'int' in a.dtype.name
5

The easiest way to do it would be to create a new numpy.dtype object each time, as it has all the necessary type normalization/standardization and equality-checking already built in. Actually, I haven't taken a look at the internals, so it's possible that it doesn't actually create a new instance of dtype for ones that numpy already has (like how using numpy.array doesn't always create a new array), which would be nicely efficient.

numpy.float64 == numpy.dtype('float64') == numpy.dtype(numpy.float64) == numpy.dtype(float)
numpy.int32 == numpy.dtype('int32') == numpy.dtype(numpy.int32) == numpy.dtype(int)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.