字符串到文字会引发不兼容的类型错误

问题描述 投票:0回答:1

在下面的代码片段上运行 mypy:

from typing import Literal, Final

def extract_literal(d2: Literal["b", "c"]) -> str:
    if d2 == "b":
        return "BA"
    if d2 == "c":
        return "BC"
    
def model(d2_name: str = "b-123") -> None:
    if d2_name[0] not in ["b", "c"]:
        raise AssertionError
    d2: Final = d2_name[0]
    print(extract_literal(d2))

抛出:

typing_test.py:17: error: Argument 1 to "extract_literal" has incompatible type "str";
expected "Literal['b', 'c']"  [arg-type]
        print(extract_literal(d2))
                              ^~
Found 1 error in 1 file (checked 1 source file)

就上下文而言,

d2_name
保证为
"b-number"
"c-number"
。根据它的第一个字母,我想输出不同的消息。

Python version: 3.11
mypy version: 1.9.0

需要进行哪些更改才能允许 mypy 通过?

python mypy
1个回答
0
投票

类型提示表明您只能将“b”或“c”两个值之一作为文字传递。因此,例如, extract_literal("b") 是有效的

© www.soinside.com 2019 - 2024. All rights reserved.