Why is numpy.dtype('float64') special?

后端 未结 2 1267
情深已故
情深已故 2021-01-05 01:48

Can someone explain the logic behind the output of the following script?

import numpy
if(numpy.dtype(numpy.float64) == None):
    print \"Surprise!!!!\"
         


        
2条回答
  •  北荒
    北荒 (楼主)
    2021-01-05 02:23

    if you want to compare an arbitrary object against exactly None in python you need to use:

    object is None
    

    Like in this case any object may override its comparison operator to not do what you are expecting.

    As for why, dtype('float64') is equivalent to None in the context of dtypes in the same way dtypes are equivalent to typestrings

    np.dtype('i4') == 'i4'
    True
    

    Equality is not identity.

    As for why dtype(None) == dtype('float64'), many functions in numpy have dtype=None keyword arguments. In most cases this means default dtype which is dtype(None). An example is np.zeros. But there are exceptions, e.g. when the dtype can be inferred from the arguments, like in the case of np.arange(10) where the default dtype will be of integer type (np.intp I think).

提交回复
热议问题