【发布时间】:2021-07-30 15:55:47
【问题描述】:
通常可以理解为可调用的返回类型是covariant。在使用可调用的属性定义类型时,我确实可以使返回类型泛型和协变:
from typing import TypeVar, Callable, Generic, Sequence
from dataclasses import dataclass
R = TypeVar("R", covariant=True)
@dataclass
class Works(Generic[R]):
call: Callable[[], R] # returns an R *or subtype*
w: Works[Sequence] = Works(lambda: []) # okay: list is subtype of Sequence
但是,Protocol 却不适用。当我以同样的方式为类型定义 Protocol 时,MyPy 拒绝了这一点——它坚持返回类型必须是invariant。
from typing import TypeVar, Callable, Protocol
R = TypeVar("R", covariant=True)
class Fails(Protocol[R]):
attribute: Callable[[], R]
$ python -m mypy so_testbed.py --pretty
so_testbed.py:5: error: Covariant type variable "R" used in protocol where invariant one is expected
class Fails(Protocol[R]):
^
Found 1 error in 1 file (checked 1 source file)
如何为尊重R 协方差的具体类型正确定义Protocol?
【问题讨论】:
标签: python mypy python-typing