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

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

There is a newer version: 4.23.0.17664
Show newest version

This rule raises an issue when a TypeVar is used as a type parameter in a type statement.

Why is this an issue?

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.

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 error use a generic type statement and remove the use of the TypeVar.

Code examples

Noncompliant code example

from typing import TypeAlias

_T = TypeVar("_T")

type MyAlias = set[_T]  # Noncompliant: a TypeVar is used as part of the type statement

Compliant solution

type MyAlias[T] = set[T]  # Compliant: the new type statement syntax is used.

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy