小编arc*_*ain的帖子

使用 types.Literal 的正确方法是什么?

我的代码看起来像这样,BDW 运行良好,没有任何错误

from typing import Literal

def verify(word: str) -> Literal['Hello XY']:
    a = 'Hello ' + word
    return a

a = verify('XY')
Run Code Online (Sandbox Code Playgroud)

虽然,当我尝试使用 mypy 进行类型检查时,它会抛出错误error: Incompatible return value type (got "str", expected "Literal['Hello XY']")

注意:要执行类型检查mypy ./filename.py,只需在 pip 安装 mypy 后执行 。

另外,当我这样做时,类型检查工作正常

from typing import Literal

def verify(word: str) -> Literal['Hello XY']:
    a = 'Hello ' + word
    return 'Hello XY' #changed here

a = verify('XY')
Run Code Online (Sandbox Code Playgroud)

我缺少什么?

python typechecking type-hinting mypy python-typing

3
推荐指数
1
解决办法
6729
查看次数

标签 统计

mypy ×1

python ×1

python-typing ×1

type-hinting ×1

typechecking ×1