typing.Literal 的正确用法是什么?

What is the correct way of using typing.Literal?

我的代码看起来像这样,它运行良好的 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