All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.py.rules.python.S6792.html Maven / Gradle / Ivy

There is a newer version: 4.23.0.17664
Show newest version

This rule raises an issue when a generic class is defined through explicit inheritance of typing.Generic instead of using the type parameter syntax.

Why is this an issue?

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.

Exceptions

This rule will only raise an issue when the Python version of the analyzed project is set to 3.12 or higher.

How to fix it

To fix this issue, make sure to use the type parameter syntax whenever defining a generic class.

Code examples

Noncompliant code example

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:
        ...

Compliant solution

class ClassA[T: str]:  # Compliant: Concise syntax for type parameter is used
    def method1(self) -> T:
        ...

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy