And*_*ndi 7 python literals mypy
我想通过使用来限制可能的输入参数typing.Literal。
下面的代码工作得很好,但是mypy有抱怨。
from typing import Literal
def literal_func(string_input: Literal["best", "worst"]) -> int:
if string_input == "best":
return 1
elif string_input == "worst":
return 0
literal_func(string_input="best") # works just fine with mypy
# The following call leads to an error with mypy:
# error: Argument "string_input" to "literal_func" has incompatible type "str";
# expected "Literal['best', 'worst']" [arg-type]
input_string = "best"
literal_func(string_input=input_string)
Run Code Online (Sandbox Code Playgroud)
不幸的是,mypy没有将类型缩小input_string为Literal["best"]。您可以通过适当的类型注释来帮助它:
input_string: Literal["best"] = "best"
literal_func(string_input=input_string)
Run Code Online (Sandbox Code Playgroud)
也许值得一提的是,pyright与您的示例配合得很好。
input_string或者,可以通过注释as来实现相同的效果Final:
from typing import Final, Literal
...
input_string: Final = "best"
literal_func(string_input=input_string)
Run Code Online (Sandbox Code Playgroud)