是否存在包含所有类型的numpy对象?

vhmi4jdf  于 2023-03-12  发布在  其他
关注(0)|答案(1)|浏览(267)

我正在编写一个函数的单元测试,该函数只接受numpy.uint8类型的numpy数组,我想测试我是否从所有其他类型中获得了正确的异常。
所以我做了这样一组:

self.supported_types = {np.uint8}
self.not_supported_types = {np.bool_,
                                    np.int8,
                                    np.int16,
                                    np.uint16,
                                    np.int32,
                                    np.uint32,
                                    np.int64,
                                    np.uint64,
                                    np.longlong,
                                    np.ulonglong,
                                    np.float16,
                                    np.float32,
                                    np.float64,
                                    np.float128,
                                    np.complex64,
                                    np.complex128,
                                    np.complex256,
                                    np.object_,
                                    np.bytes_,
                                    np.str_,
                                    np.void,
                                    np.datetime64,
                                    np.timedelta64}

我想知道是否有一种方法可以得到一个包含numpy所有类型的列表,而不用将所有类型都写为:

all_types = numpy.something() # does this exist?
not_supported = all_types.remove(numpy.uint8)
icomxhvb

icomxhvb1#

您可以使用np.dtype.__subclasses__()

[x.type for x in np.dtype.__subclasses__()]

输出:

[numpy.bool_,
 numpy.int8,
 numpy.uint8,
 numpy.int16,
 numpy.uint16,
 numpy.int32,
 numpy.uint32,
 numpy.int64,
 numpy.uint64,
 numpy.longlong,
 numpy.ulonglong,
 numpy.float32,
 numpy.float64,
 numpy.float128,
 numpy.complex64,
 numpy.complex128,
 numpy.complex256,
 numpy.object_,
 numpy.bytes_,
 numpy.str_,
 numpy.void,
 numpy.datetime64,
 numpy.timedelta64,
 numpy.float16,
 int,
 float,
 complex]

在您的情况下:

supported_types = {np.uint8}
not_supported_types = ({x.type for x in np.dtype.__subclasses__()}
                       - supported_types - {int, complex, float})

输出:

{numpy.bool_,
 numpy.bytes_,
 numpy.complex128,
 numpy.complex256,
 numpy.complex64,
 numpy.datetime64,
 numpy.float128,
 numpy.float16,
 numpy.float32,
 numpy.float64,
 numpy.int16,
 numpy.int32,
 numpy.int64,
 numpy.int8,
 numpy.longlong,
 numpy.object_,
 numpy.str_,
 numpy.timedelta64,
 numpy.uint16,
 numpy.uint32,
 numpy.uint64,
 numpy.ulonglong,
 numpy.void}

相关问题