Comparing Numpy dtypes in sets vs tuples?

Viewed 81

So, I happened upon this strange issue where seeing if a set contains a Numpy dtype object vs. seeing if a tuple contains one gives different results:

In [1]: x = np.zeros(8)

In [2]: x.dtype
Out[2]: dtype('float64')

In [3]: x.dtype in (np.float32, np.float64)
Out[3]: True

In [4]: x.dtype in {np.float32, np.float64}
Out[4]: False

Why does this happen? What's preventing set().__contains__() from returning True when looking at numpy.dtype objects?

1 Answers

Checking membership in a set uses __hash__() instead of __eq__(). In this case, it simply turns out that the objects are equal to each other but generate different hashes:

In [1]: np.float64 == np.dtype(np.float64)
Out[1]: True

In [2]: hash(np.float64)
Out[2]: 8793996338852

In [3]: hash(np.dtype(np.float64))
Out[3]: -7365930899603730638
Related