This rule raises an issue when a TypeVar is used as a type parameter in a type statement.
Prior to Python 3.12, generic type aliases were defined as follows:
from typing import TypeAlias, TypeVar
_T = TypeVar("_T")
MyAlias: TypeAlias = set[_T]
Python 3.12 introduced the type statement to facilitate the use of such type aliases, allowing for less confusing and more concise
code:
type MyAlias[T] = set[T]
Python is transitioning away from explicit TypeVar declaration from Python 3.12 onward. This means that Type alias expressions are not
allowed to use TypeVar allocated with an explicit constructor call:
from typing import TypeVar
_T = TypeVar("_T")
type MyAlias[A: str] = dict[A, _T] # Type checker error would be raise
It is a good practice to use the new syntax only, as it fulfills all the requirements of the TypeVar declaration in a more concise and
readable way.
This rule will only raise an issue when the Python version of the analyzed project is set to 3.12 or higher.
To fix this error use a generic type statement and remove the use of the TypeVar.
from typing import TypeAlias
_T = TypeVar("_T")
type MyAlias = set[_T] # Noncompliant: a TypeVar is used as part of the type statement
type MyAlias[T] = set[T] # Compliant: the new type statement syntax is used.