Creating numpy.dtype from string without incosistencies

181 Views Asked by At

Does numpy have a way to create dtypes from a string? numpy.dtype() is almost what I need, but it creates an inconsistency:

import numpy as np

dtype1 = np.dtype('float32')
dtype2 = np.float32

# This works (prints "same")
if dtype1 == dtype2:
    print("same")

# I want the code in the line below to produce a set with one item
# However, the resulting set is: {dtype('float32'), <class 'numpy.float32'>}
dtypes = {dtype1, dtype2}

# One way to fix the above is to write the following, but this is ugly
dtypes = {np.empty(1, dtype1).dtype, np.empty(1, dtype2).dtype}

Is there an elegant way to fix the above problem?

Thank you

1

There are 1 best solutions below

0
hpaulj On BEST ANSWER

While your two objects do the same thing when used as the dtype argument, they are not the same thing, or even the same kind of thing:

In [51]: np.dtype('float32')                                                                         
Out[51]: dtype('float32')
In [52]: np.float32                                                                                  
Out[52]: numpy.float32
In [53]: type(np.dtype('float32'))                                                                   
Out[53]: numpy.dtype
In [54]: type(np.float32)                                                                            
Out[54]: type

One is an instance of np.dtype, the other is a function.

np.empty(1, 'f').dtype is another string that produces the desired dtype, but clearly won't match in set.

Using the function:

In [59]: np.float32(1).dtype                                                                         
Out[59]: dtype('float32')