Hi everyone,
Type variables allow to specify their variance at construction time, i.e variance is currently a property of a type variable. This is problematic for cases when a type variable is used outside of a generic class. For example,
T_co = TypeVar("T", covariant=True) def callback(value: T_co): ...
or
ListT = list[T_co]
I am curious, if we could instead deprecate the variance parameters and make variance local to the generic class definition. Specifically,
* all type variables are created invariant; * a type variable can be annotated as covariant and contravariant using unary + and - operators respectively; * these operators are only allowed when a type variable is referenced in the bases of a class definition.
For example, here
T = TypeVar("T") class Source(Generic[+T]): ...
the class Source is covariant in T.
Wdyt?
Sergei
I completely agree, and pointed this out earlier in an gh issue: https://github.com/python/typing/issues/813 . I am currently working on drafting a PEP that introduces this syntax. You can find the current draft here: https://github.com/jorenham/peps/blob/master/pep-9999.rst Any feedback on the draft PEP is welcome, see https://github.com/jorenham/peps/issues/1