This rule raises an issue when a generic class is defined through explicit inheritance of typing.Generic instead of using the type
parameter syntax.
Through PEP 695, Python 3.12 introduces the type parameter syntax to allow for a more compact and explicit way to define generic classes and functions.
Prior to Python 3.12, defining a generic class would be done through the following syntax:
from typing import Generic, TypeVar
_T_co = TypeVar("_T_co", covariant=True, bound=str)
class ClassA(Generic[_T_co]):
def method1(self) -> _T_co:
...
Since Python 3.12, it can be done with the following syntax:
class ClassA[T: str]:
def method1(self) -> T:
...
Using the former syntax requires importing TypeVar and Generic symbols from the typing module. It also
requires the explicit definition of a type variable in the global scope, with a redundant name provided in quotes (T = TypeVar("T")).
This makes the definition of generic classes verbose and confusing.
It is therefore recommended to use the type parameter syntax when working with Python 3.12 and later.
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, make sure to use the type parameter syntax whenever defining a generic class.
from typing import Generic, TypeVar
_T_co = TypeVar("_T_co", covariant=True, bound=str)
class ClassA(Generic[_T_co]): # Noncompliant: Explicit definition of a TypeVar and inheritance from typing.Generic is verbose
def method1(self) -> _T_co:
...
class ClassA[T: str]: # Compliant: Concise syntax for type parameter is used
def method1(self) -> T:
...