Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. So if Button extends Widget, calling example(Button()) returns type 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. Upon further research I found a note in 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.

However if I try to define a generic function without the covariant argument as specified in the note:

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).

How can I achieve this?

like image 908
Ian Avatar asked Aug 08 '26 22:08

Ian


1 Answers

I was able to find the answer in the MyPy docs. Turns out I was looking for bound, not covariant. This can be done like so:

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

def example(widget: T) -> T:
  ...
like image 64
Ian Avatar answered Aug 11 '26 12:08

Ian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!