简体   繁体   English

如何在 Python 中定义通用协变 function?

[英]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 or contravariant keyword arguments.后者应该只使用没有covariantcontravariant关键字 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?我怎样才能做到这一点?

I was able to find the answer in the MyPy docs .我能够在MyPy 文档中找到答案。 Turns out I was looking for bound , not covariant .原来我在寻找bound ,而不是covariant This can be done like so:这可以这样做:

T = TypeVar('T', bound=Widget)

def example(widget: T) -> T:
  ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM