This rule raises an issue when a TypeVar is used in a function instead of the generic function type syntax.
Prior to Python 3.12 functions using generic types were created as follows:
from typing import TypeVar
_T = TypeVar("_T")
def func(a: _T, b: _T) -> _T:
...
This snippet of code can be confusing and difficult to read. This is why is it a good idea to use the new type parameter syntax of Python 3.12 that
allows for a more concise and more readable code by removing the TypeVar and its import statement:
def func[T](a: T, b: T) -> T:
...
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 issue, replace the usage of a TypeVar as a parameter type with the generic type parameter syntax.
from typing import TypeVar
_T = TypeVar("_T", bound=str)
def func(a: _T, b: int) -> _T: # Noncompliant: the usage of a TypeVar could be simplified with a generic type parameter.
...
def func[T: str](a: T, b: int) -> T: # Compliant: the code is clear and concise.
...