python - 如何在 Python 中定义通用协变函数?

标签 python python-3.x function generics python-typing

我想定义一个函数 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)。

我怎样才能做到这一点?

最佳答案

我能够在 MyPy docs 中找到答案.原来我在寻找 bound,而不是 covariant。这可以像这样完成:

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

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

关于python - 如何在 Python 中定义通用协变函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58379692/

相关文章:

python - 如何在 plotly 中将单行添加到散点图?

python - 数字作为 statsmodels.formula.api 无法识别的变量名称

Python3 - 将字典嵌套到 JSON

javascript - JS 菜鸟——为什么 document.onclick 无法正常工作?

python - 如何分组和计数

python - 这给出了正确的标准偏差 ..numpy.std() 或 statistics.stdev()

python - 通过python播放音频

python - 在 MyClass.my_attribute 中使用点表示法时会调用什么方法?

Excel 搜索字符串

javascript - 访问另一个函数中的变量,返回未定义 - JavaScript