mypy v0.812 不兼容类型“str”;预期“联合[文字['a'],联合[文字['b']..]

问题描述

有没有办法在不更改 class Config 的情况下让 mypy 对这段代码感到满意,目前我无法更改该类(将 typer 用于 cli 应用程序)。我知道我可以使用 # type: ignore ,但还有其他解决方案吗?

"""
mypy --version
mypy 0.812
"""
from enum import Enum
from pathlib import Path

from typing_extensions import Literal


class Config(str,Enum):
  Debug = 'Debug'
  Release = 'Release'


BuildMode = Literal["ASAN","ubsan","Coverage","Release","Debug"]


def run_c_tests(results_dir: Path,mode: BuildMode):
  ...


configuration = Config.Debug

# mypy error: Argument 2 to "run_c_tests" has incompatible type "str"; expected "Union[Literal['ASAN'],Literal['ubsan'],Literal['Coverage'],Literal['Release'],Literal['Debug']]"
run_c_tests(Path('apath'),configuration.value)

Mypy v0.782 不会抱怨上面的代码,但 0.812 会。

解决方法

我遇到了与您类似的问题,并使用 Final 注释修复了它。例如

from typing import Final

STRICT: Final = "strict"

我在这里找到了提示:https://stackoverflow.com/a/63892386/3787959

Annotating a variable as Final indicates that its value will not be substituted for a value of similar type. This makes it correct to infer the type as the specific Literal value,instead of just the general type.