当尝试使用类型的 TypeVar 来启用具有返回类型的泛型时,我遇到了 mypy 错误,即bound在比较字典的类型和函数的预期返回类型时未考虑参数。
下面是我面临的情况的一个例子:
from typing import Dict, List, Type, TypeVar
class Bird:
def call(self):
print(self.sound)
class Chicken(Bird):
def __init__(self):
self.sound = "bok bok"
class Owl(Bird):
def __init__(self):
self.sound = "hoot hoot"
T = TypeVar("T", bound=Bird)
class Instantiator:
def __init__(self, birds: List[Type[Bird]]):
self._bird_map: Dict[Type[Bird], Bird] = {}
for bird in birds:
self._bird_map[bird] = bird()
def get_bird(self, bird_type: Type[T]) -> T:
return self._bird_map[bird_type]
Run Code Online (Sandbox Code Playgroud)
运行 mypy 验证器将显示:temp.py:29: error: Incompatible return value type (got "Bird", expected "T")
它 …