python Pylance中Union类型变量的类型推断问题

4xrmg8kj  于 2023-06-20  发布在  Python
关注(0)|答案(1)|浏览(127)

我正在编写一个具有不同行为的函数,具体取决于参数是标量还是NumPy数组。然而,我得到了以下两个输入错误,我不知道如何解决:

  1. Expression of type "generic | bool | int | float | complex | str | bytes | memoryview" cannot be assigned to return type "float" Type "generic | bool | int | float | complex | str | bytes | memoryview" cannot be assigned to type "float" "bytes" is incompatible with "float" PylancerreportGeneralTypeIssues
  2. "__ getitem __" method not defined on type "float" PylancereportGeneralTypeIssues**。
    如何让Pylance知道如果代码到达if语句中的表达式,x应该是float,如果到达else表达式,x应该是NumPy数组?
    示例代码:
import numpy as np
import numpy.typing as npt

def func(x: float | npt.NDArray[np.float64]) -> float:
    if np.isscalar(x):
        return x     # Error 1)
    else:
        return x[0]  # Error 2)

def main():
    x = 0.4
    print(func(x))

if __name__ == "__main__":
    main()
ia2d9nvy

ia2d9nvy1#

一种可能性是添加assertcast以强制将其视为浮点型。以下任何一项都将起作用:

assert isinstance(x, float)
x = cast(float, x)
x = float(x)  # type: ignore

一起来:

def func(x: float | npt.NDArray[np.float64]) -> float:
    if np.isscalar(x):
        assert isinstance(x, float)
        return x
    else:
        assert not isinstance(x, float)
        return x[0]

...虽然,更直接的是:

def func(x: float | npt.NDArray[np.float64]) -> float:
    return x if isinstance(x, float) else x[0]

...除非您依赖np.isscalar来执行这些类型签名所建议的以外的操作。

相关问题