如何在Python中定义泛型协变函数?

2024-04-26 20:27:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我想定义一个函数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 or contravariant keyword arguments.

但是,如果我试图定义一个泛型函数,而不使用注释中指定的协变参数:

T_co = TypeVar('T_co', Widget)

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

我只能将Widget类型的值传递给函数(而不是Button)。你知道吗

我怎样才能做到这一点?你知道吗


Tags: or函数类型参数定义exampledefbutton