【发布时间】:2022-11-24 16:44:08
【问题描述】:
我想通过使用 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)
【问题讨论】:
-
input_string的推断类型只是str,如果您不想内联它,则必须显式提供更窄的类型以防止重新分配给不是“最佳”(或“最差”)的值). -
mypy 在您的情况下是正确的:
input_string不是文字,而是str类型的变量。尝试使用字符串输入类型定义 literal_func