(Python,Numpy:类型提示),如何正确地将“integer”值转换为“_DType@clip”?

5sxhfpxr  于 2023-08-05  发布在  Python
关注(0)|答案(3)|浏览(87)

我遇到了Numpy (version 1.25)类型提示的问题。假设下面的代码(/tmp/asdf.py):

import numpy as np

tx: int = 32 
out_tx = np.clip(
        tx,
        0, 
        100,
        )

字符串
pyright出现以下错误:

$ pyright /tmp/asdf.py
/tmp/asdf.py
  /tmp/asdf.py:5:9 - error: Argument of type "Literal[32]" cannot be assigned to parameter "a" of type "ndarray[_DType@clip]" in function "clip"
    "Literal[32]" is incompatible with "ndarray[_DType@clip]" (reportGeneralTypeIssues)
  /tmp/asdf.py:6:9 - error: Argument of type "Literal[0]" cannot be assigned to parameter "a_min" of type "_DType@clip" in function "clip"
    Type "Literal[0]" is incompatible with constrained type variable "_DType" (reportGeneralTypeIssues)
  /tmp/asdf.py:7:9 - error: Argument of type "Literal[100]" cannot be assigned to parameter "a_max" of type "_DType@clip" in function "clip"
    Type "Literal[100]" is incompatible with constrained type variable "_DType" (reportGeneralTypeIssues)
3 errors, 0 warnings, 0 informations

  • 如何正确地将"integer"转换为Numpy's "_DType@clip",这样pyright就不会输出这些消息?

更新:

  • 我忘了说我是numpy v1.25
  • numpy v.1.24上,pyright不输出任何警告
  • 我知道上面的代码是有效的。
  • 我只是在寻找最安全的编写方式,因为我真的很喜欢静态分析器/链接器/LSP。
oyxsuwqo

oyxsuwqo1#

答案1

Pyright应该不会返回错误,首先尝试用pip install --upgrade --force-reinstall pyright numpy重新安装pyright和numpy。
如果它不起作用,如pyright文档中所解释的:
不管搜索路径如何,Pyright总是尝试在返回到python源(“.py”)文件之前使用类型存根(“.pyi”)文件解析导入。
Numpy有这些.pyi文件,对于以整数为参数的clip函数,我们有https://github.com/numpy/numpy/blob/main/numpy/core/fromnumeric.pyi#L397-L408:

@overload
def clip(
    a: _ScalarLike_co,
    a_min: None | ArrayLike,
    a_max: None | ArrayLike,
    out: None = ...,
    *,
    dtype: None = ...,
    where: None | _ArrayLikeBool_co = ...,
    order: _OrderKACF = ...,
    subok: bool = ...,
    signature: str | tuple[None | str, ...] = ...,
) -> Any: ...

字符串
有了这个,你的案子就不会有任何错误了。
所以看起来你的pyright考虑了一些存根文件(否则请求的类型将是Any,而不是“_DType@clip”),但不是来自Numpy的那些。您可以尝试使用选项来找到它,这些选项类似于最知名的IDE的“转到定义”。

答案二

您可以使用typing.cast,但这意味着对pyright撒谎,以匹配已经不好的clip函数的签名。

import typing
import numpy as np

tx: int = 32
out_tx = np.clip(
        typing.cast(np.ndarray, tx),
        typing.cast(np.ndarray, 0),
        typing.cast(np.ndarray, 1),
        )


或者代替np.ndarray,每个不返回警告的类型

yxyvkwin

yxyvkwin2#

显然,以下修复了最后2个警告:

import numpy as np

tx: int = 32
out_tx = np.clip(
    np.int32(tx),    # still expects array, produces warning
    np.int32(0),     # this fixed
    np.int32(100),   # this fixed
)

字符串

tvmytwxo

tvmytwxo3#

我发现了为什么pyright在不应该输出错误的时候输出错误:
原因是我还安装了data-science-types包。而且它似乎已经覆盖了numpy的键入。
卸载后(使用pip3 uninstall data-science-typespyright不会再次输出此错误。

相关问题