[英]How can I define a generic covariant function in Python?
I want to define a function example
that takes an argument of type Widget
or anything that extends Widget
and returns the same type as the argument.我想定义一个 function example
,该示例采用Widget
类型的参数或任何扩展Widget
并返回与参数相同类型的参数。 So if Button
extends Widget
, calling example(Button())
returns type Button
.因此,如果Button
扩展Widget
,则调用example(Button())
会返回Button
类型。
I tried the following:我尝试了以下方法:
T_co = TypeVar('T_co', Widget, covariant=True)
def example(widget: T_co) -> T_co:
...
However the type checker (Pyright) ignores the covariance.但是类型检查器(Pyright)忽略了协方差。 Upon further research I found a note in PEP 484 :经过进一步研究,我在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.注意:协变或逆变不是类型变量的属性,而是使用此变量定义的通用 class 的属性。 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.后者应该只使用没有covariant
或contravariant
关键字 arguments 的类型变量来定义。
However if I try to define a generic function without the covariant argument as specified in the note:但是,如果我尝试在没有注释中指定的协变参数的情况下定义通用 function :
T_co = TypeVar('T_co', Widget)
def example(widget: T_co) -> T_co:
...
I can only pass values of type Widget
to the function (not Button
).我只能将Widget
类型的值传递给 function (不是Button
)。
How can I achieve this?我怎样才能做到这一点?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.