如何显式告诉 mypy 变量的正确类型?

How to explicitly tell mypy the correct type of a variable?

我选择了一个 pandas 数据框的值,变量的类型是字符串。在一个函数中,我 return 这个值,我已经将该值注释为 str.

def get_item_name(code: str) -> str:
    item = df.loc[code, "item_name"]
    return item

然而,mypy 给了我以下警告:

Expression of type "Scalar" cannot be assigned to return type "str"
Type "Scalar" cannot be assigned to type "str" "bytes" is incompatible with "str"PylancereportGeneralTypeIssues

有没有办法明确告诉 mypy 变量项的正确类型是字符串?

如果我使用 str(df.loc[code, "item_name"]),我会收到警告消失,但这使得代码看起来值可能是一个数字,但我们将其转换为字符串,但事实并非如此,因为该值已经是字符串.

如果实在有把握,可以用cast。不过你应该小心这一点。

from typing import cast

def get_item_name(code: str) -> str:
    item = df.loc[code, "item_name"]
    return cast(str, item)