不确定为什么会生成 mypy "Incompatible types in assignment"

Not sure why this generates a mypy "Incompatible types in assignment"

让我感到困惑的简单示例:

from typing import Callable, List, Union

Value = Union[bool, int, str]
Helper = Callable[[Value], List[Value]]


def func_with_alias(aa: Value) -> List[Value]:
    return []


def func_with_type(aa: bool) -> List[Value]:
    return []


your_func1: Helper = func_with_alias
your_func2: Helper = func_with_type

mypy 抱怨“your_func2”的类型不兼容: error: Incompatible types in assignment (expression has type "Callable[[bool], List[Union[bool, int, str]]]", variable has type "Callable[[Union[bool, int, str]], List[Union[bool, int, str]]]")

为什么它不让我这样做,因为 boolUnion[bool, int, str] 中?

❯ mypy --version
mypy 0.782

让我们看看您对类型定义的看法:

Value = Union[bool, int, str]

A Value can be either a boolean, an integer or a string.

Helper = Callable[[Value], List[Value]]

A Helper takes a Value and returns a List of Values.

现在错误的赋值:

def func_with_type(aa: bool) -> List[Value]:
    return []

your_func2: Helper = func_with_type

func_with_type 只接受布尔值,但您将其分配给应该也能接受整数或字符串的类型。


要了解为什么这没有意义,请考虑 Helper 函数的以下 consumer

def consumer(func: Helper) -> List[Value]:
     return func("Hello, world!")

一个Helper可以带一个Value,可以是boolintstr,所以这个用法应该没问题。但是func_with_type只接受一个bool,所以不能这样调用,所以我们不能认为它是一个Helper


What I am actually doing is building a dispatch dict that has a key of the actual class (say bool, int, or str) and a value of a function that handles it. The return is a list of Value (eg, bool, int, or str).

可能你想要的是一个generic函数,其中通用类型受联合约束:

T = TypeVar('T', bool, int, str)
Helper = Callable[[T], List[T]]