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
orcontravariant
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?
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:
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.