我遇到了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。
3条答案
按热度按时间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:
字符串
有了这个,你的案子就不会有任何错误了。
所以看起来你的pyright考虑了一些存根文件(否则请求的类型将是Any,而不是“_DType@clip”),但不是来自Numpy的那些。您可以尝试使用选项来找到它,这些选项类似于最知名的IDE的“转到定义”。
答案二
您可以使用
typing.cast
,但这意味着对pyright撒谎,以匹配已经不好的clip
函数的签名。型
或者代替
np.ndarray
,每个不返回警告的类型yxyvkwin2#
显然,以下修复了最后2个警告:
字符串
tvmytwxo3#
我发现了为什么
pyright
在不应该输出错误的时候输出错误:原因是我还安装了
data-science-types
包。而且它似乎已经覆盖了numpy
的键入。卸载后(使用
pip3 uninstall data-science-types
)pyright
不会再次输出此错误。