【问题标题】:Python type hints: How to use Literal with strings to conform with mypy?Python 类型提示:How to use Literal with strings to conform with mypy?
【发布时间】: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

标签: python mypy literals


【解决方案1】:

很遗憾,我的不会将 input_string 的类型缩小为 Literal["best"]。您可以通过适当的类型注释来帮助它:

input_string: Literal["best"] = "best"
literal_func(string_input=input_string)

也许值得一提的是,pyright 与您的示例配合得很好。


或者,可以通过将 input_string 注释为 Final 来实现相同的目的:

from typing import Final, Literal

...

input_string: Final = "best"
literal_func(string_input=input_string)

【讨论】:

    猜你喜欢
    • 2022-12-02
    • 2022-12-27
    • 2022-12-28
    • 2022-12-01
    • 2022-12-26
    • 2022-12-27
    • 2022-12-02
    • 2022-12-19
    • 2022-12-26
    相关资源
    最近更新 更多