让我困惑的简单例子:
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]]]")
为什么它不让我这样做,因为bool
在Union[bool, int, str]
中?
❯ mypy --version
mypy 0.782
让我们看看您对类型定义的看法:
Value = Union[bool, int, str]
值可以是布尔值、整数或字符串。
Helper = Callable[[Value], List[Value]]
帮助程序获取一个值并返回一个值列表。
现在错误的赋值:
def func_with_type(aa: bool) -> List[Value]:
return []
your_func2: Helper = func_with_type
func_with_type
只接受布尔值,但您将其分配给一个应该也能接受整数或字符串的类型。
要了解为什么这没有意义,请考虑Helper
函数的以下消费者:
def consumer(func: Helper) -> List[Value]:
return func("Hello, world!")
Helper
可以取Value
,它可以是bool
、int
或str
,所以这种用法应该很好。但是func_with_type
只接受一个bool
,所以不能用这种方式调用,所以我们不能认为它是Helper
。
我实际正在做的是构建一个调度dict,该dict具有实际的类(比如bool、int或str(和函数的值处理它。返回值是Value(例如,bool、int或str(。
您可能想要一个泛型函数,其中泛型类型受并集约束:
T = TypeVar('T', bool, int, str)
Helper = Callable[[T], List[T]]