我想定义一个函数example
,它接受类型为Widget
的参数或任何扩展Widget
并返回与参数相同类型的参数。所以如果Button
扩展Widget
,调用example(Button())
返回类型Button
。你知道吗
我尝试了以下方法:
T_co = TypeVar('T_co', Widget, covariant=True)
def example(widget: T_co) -> T_co:
...
但是类型检查器(Pyright)忽略协方差。经过进一步研究,我在PEP 484中发现了一个注释:
Note: Covariance or contravariance is not a property of a type variable, but a property of a generic class defined using this variable. Variance is only applicable to generic types; generic functions do not have this property. The latter should be defined using only type variables without
covariant
orcontravariant
keyword arguments.
但是,如果我试图定义一个泛型函数,而不使用注释中指定的协变参数:
T_co = TypeVar('T_co', Widget)
def example(widget: T_co) -> T_co:
...
我只能将Widget
类型的值传递给函数(而不是Button
)。你知道吗
我怎样才能做到这一点?你知道吗
我在MyPy docs中找到了答案。原来我在找
bound
,不是covariant
。可以这样做:相关问题 更多 >
编程相关推荐