无法使用Pandas DataFrame迭代元组访问类型元组[Any,...]的成员(Pyright-langserver,带有Neovim 0.7)

y3bcpkx1  于 2023-03-06  发布在  其他
关注(0)|答案(1)|浏览(79)

我在Neovim v0.7.0中使用了pright-langserver。它运行良好,只是我不知道如何在以下情况下正确注解类型。

import pandas as pd

df = pd.DataFrame({'num_legs': [4, 2], 'num_wings': [0, 2]},index=['dog', 'hawk'])

for row in df.itertuples():
    print(row.num_legs) # ■ Cannot access member "num_legs" for type "tuple[Any, ...]"    Member "num_legs" is unknown

如您所见,我添加了一条注解,显示了pyright报告的错误:Cannot access member "num_legs" for type "tuple[Any, ...]"   Member "num_legs" is unknown
这段代码是有效的,因为它打印了4,然后打印了2,正如我所期望的那样。我如何满足类型检查呢?

shyt4zoc

shyt4zoc1#

我还没有找到解决类型问题的方法(Pandas只是将类型作为泛型元组),但是至少有两种方法可以抑制错误报告。
1.告诉Pyrright到ignore the error

for row in df.itertuples():
    print(row.num_legs)  # # pyright: ignore [reportGeneralTypeIssues]

1.将类型cast()为Any以关闭对象的类型冲突

from typing import cast

for row in df.itertuples():
    row: Any = cast(Any, row)
    print(row.num_legs)

相关问题