在numpy中,许多对象的构造函数接受"array_like"作为第一个参数.是否有这样一个对象的定义,要么作为抽象元类,要么应该包含方法的文档?
unu*_*tbu 44
事实证明,几乎任何东西在技术上都是类似阵列的."类似数组"更多地是关于如何解释输入的声明,而不是对输入的限制; 如果参数被记录为类似数组,NumPy将尝试将其解释为数组.
除了近似重复的数组之外,没有类似数组的正式定义 - 类似数组的任何Python对象都np.array
可以转换为ndarray
.要超越这个范围,您需要学习源代码.
NPY_NO_EXPORT PyObject *
PyArray_FromAny(PyObject *op, PyArray_Descr *newtype, int min_depth,
int max_depth, int flags, PyObject *context)
{
/*
* This is the main code to make a NumPy array from a Python
* Object. It is called from many different places.
*/
PyArrayObject *arr = NULL, *ret;
PyArray_Descr *dtype = NULL;
int ndim = 0;
npy_intp dims[NPY_MAXDIMS];
/* Get either the array or its parameters if it isn't an array */
if (PyArray_GetArrayParamsFromObject(op, newtype,
0, &dtype,
&ndim, dims, &arr, context) < 0) {
Py_XDECREF(newtype);
return NULL;
}
...
Run Code Online (Sandbox Code Playgroud)
特别有趣的是PyArray_GetArrayParamsFromObject
,其注释枚举了所np.array
期望的对象类型:
NPY_NO_EXPORT int
PyArray_GetArrayParamsFromObject(PyObject *op,
PyArray_Descr *requested_dtype,
npy_bool writeable,
PyArray_Descr **out_dtype,
int *out_ndim, npy_intp *out_dims,
PyArrayObject **out_arr, PyObject *context)
{
PyObject *tmp;
/* If op is an array */
/* If op is a NumPy scalar */
/* If op is a Python scalar */
/* If op supports the PEP 3118 buffer interface */
/* If op supports the __array_struct__ or __array_interface__ interface */
/*
* If op supplies the __array__ function.
* The documentation says this should produce a copy, so
* we skip this method if writeable is true, because the intent
* of writeable is to modify the operand.
* XXX: If the implementation is wrong, and/or if actual
* usage requires this behave differently,
* this should be changed!
*/
/* Try to treat op as a list of lists */
/* Anything can be viewed as an object, unless it needs to be writeable */
}
Run Code Online (Sandbox Code Playgroud)
因此,通过研究源代码,我们可以得出类似数组的结论
__array_struct__
或__array_interface__
接口的对象,或__array__
功能的对象,或object
dtype 的0维数组.NumPy 1.21 引入了numpy.typing.ArrayLike
.
在此提交中最初定义如下:
class _SupportsArray(Protocol):
@overload
def __array__(self, __dtype: DtypeLike = ...) -> ndarray: ...
@overload
def __array__(self, dtype: DtypeLike = ...) -> ndarray: ...
ArrayLike = Union[bool, int, float, complex, _SupportsArray, Sequence]
Run Code Online (Sandbox Code Playgroud)
ArrayLike
但是,可以在以下位置找到的更新定义numpy/_typing/_array_like.py
:
_ArrayLike = Union[
_NestedSequence[_SupportsArray[_DType]],
_NestedSequence[_T],
]
ArrayLike = Union[
_RecursiveSequence,
_ArrayLike[
"dtype[Any]",
Union[bool, int, float, complex, str, bytes]
],
]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
20445 次 |
最近记录: |