我不明白应该如何在代码中使用 ArrayLike。如果检查 mypy,当我尝试在不调用强制转换的情况下使用变量进行任何操作时,我会不断收到错误。我正在尝试定义与 ndarray 以及常规列表一起使用的函数签名。
例如下面的代码
import numpy.typing as npt
import numpy as np
from typing import Any
def f(a: npt.ArrayLike) -> int:
return len(a)
def g(a: npt.ArrayLike) -> Any:
return a[0]
print(f(np.array([0, 1])), g(np.array([0, 1])))
print(f([0, 1]), g([0, 1]))
Run Code Online (Sandbox Code Playgroud)
给我 f() 和 g() 的这些错误:
Argument 1 to "len" has incompatible type "Union[_SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], bool, int, float, complex, str, bytes, _NestedSequence[Union[bool, int, float, complex, str, bytes]]]"; expected "Sized" [arg-type]
Value of type "Union[_SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], bool, int, float, complex, str, bytes, …Run Code Online (Sandbox Code Playgroud)