gpt4 book ai didi

python - numpy.ndarray 的类型提示/注释 (PEP 484)

转载 作者:行者123 更新时间:2023-12-03 06:11:18 59 4
gpt4 key购买 nike

有没有人为特定的 numpy.ndarray 实现类型提示类?

现在,我正在使用 typing.Any ,但最好有更具体的内容。

例如,如果 NumPy 人们添加了 type alias为他们array_like对象类。更好的是,通过 dtype 实现支持级别,以便支持其他对象,以及 ufunc .

最佳答案

Numpy 1.21 包含一个具有 NDArray 泛型类型的 numpy.typing 模块。

<小时/>
来自Numpy 1.21 docs :
numpy.typing.NDArray = numpy.ndarray[typing.Any, numpy.dtype[+ScalarType]]

A generic version of np.ndarray[Any, np.dtype[+ScalarType]].

Can be used during runtime for typing arrays with a given dtype and unspecified shape.

Examples:

>>> import numpy as np
>>> import numpy.typing as npt

>>> print(npt.NDArray)
numpy.ndarray[typing.Any, numpy.dtype[+ScalarType]]

>>> print(npt.NDArray[np.float64])
numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]

>>> NDArrayInt = npt.NDArray[np.int_]
>>> a: NDArrayInt = np.arange(10)

>>> def func(a: npt.ArrayLike) -> npt.NDArray[Any]:
... return np.array(a)

截至 2022 年 9 月 5 日,对形状的支持仍在进行中,根据 numpy/numpy#16544 .

关于python - numpy.ndarray 的类型提示/注释 (PEP 484),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35673895/

59 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com