PyArray_FromAny ignores newtype with memoryview
Author: superbobryCreated May 13, 2019Updated Sep 30, 2026
Labelscomponent: numpy._core07 - Deprecationsustain-2026
PyArray_FromAny does not necessarily return an array of the requested DType. Specifically, when called with a memoryview object, the DType is ignored (i.e. there is no validation nor casting).
Reproducing code example:
The following snippet works because __array__ allows for casting
import numpy as np
>>> import numpy as np
>>> condition = np.array([])
>>> condition.dtype
dtype('float64')
>>> arr = np.array([])
>>> np.compress(condition, arr)
array([], dtype=float64)However, if we wrap condition in a memoryview we get an error
>>> np.compress(memoryview(condition), arr)
Traceback (most recent call last):
File "[...]/numpy/core/fromnumeric.py", line 56, in _wrapfunc
return getattr(obj, method)(*args, **kwds)
TypeError: Cannot cast array data from dtype('float64') to dtype('bool') according to the rule 'safe'Numpy/Python version information:
>>> import sys, numpy; print(numpy.__version__, sys.version)
1.16.3 3.6.5 (default, Mar 31 2018, 05:34:57)
[GCC 7.3.0]Source: numpy/numpy