我的代码看起来像这样,BDW 运行良好,没有任何错误
from typing import Literal
def verify(word: str) -> Literal['Hello XY']:
a = 'Hello ' + word
return a
a = verify('XY')
尽管,当我尝试使用 mypy 进行类型检查时,它会抛出错误
error: Incompatible return value type (got "str", expected "Literal['Hello XY']")
注意:要执行类型检查,只需在 pip 安装 mypy 后执行
mypy ./filename.py
即可。
ALSO,当我这样做时,类型检查工作正常
from typing import Literal
def verify(word: str) -> Literal['Hello XY']:
a = 'Hello ' + word
return 'Hello XY' #changed here
a = verify('XY')
我错过了什么?
word
可以是任何字符串,所以这似乎是 mypy 抱怨的一件好事,因为它无法猜测您总是会使用适当的参数来调用它。换句话说,对于 mypy,如果将 'Hello '
与一些 str
连接起来,它可以给出任何 str
而不仅仅是 'Hello XY'
。
您可以检查该函数是否被正确调用,而是输入
word
和文字:
from typing import Literal, cast
hello_t = Literal['Hello there', 'Hello world']
def verify(word: Literal['there', 'world']) -> hello_t:
a = cast(hello_t, 'Hello ' + word)
return a
a = verify('there') # mypy OK
a = verify('world') # mypy OK
a = verify('you') # mypy error
请注意,仍然需要强制转换,因为 mypy 无法猜测
'Hello '
与 Literal['there', 'world']
的串联是 hello_t
类型。