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

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

There is a newer version: 4.23.0.17664
Show newest version

This rule raises an issue when a type alias is declared outside of a type statement.

Why is this an issue?

Since Python 3.12 the keyword type is used to defined type aliases. It replaces the following construct:

from typing import TypeAlias, TypeVar

_T = TypeVar("_T")

MyTypeAlias: TypeAlias = set[_T]

Using the type statement to define type aliases allows for a more concise code and thus better readability. This also makes it possible to declutter the code, as imports from the typing module (TypeAlias and TyperVar) can be removed.

type MyTypeAlias[T] = set[T]

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

Use a type statement to declare the TypeAlias instead of using a regular assignment.

Code examples

Noncompliant code example

from typing import TypeAlias

MyStringAlias: TypeAlias = str # Noncompliant: this TypeAlias can be more concise with the help of the type statement.

_T = TypeVar("_T")
MyGenericAlias: TypeAlias = list[_T]  # Noncompliant: the type statement can help replace both the TypeVar and the TypeAlias statements.

Compliant solution

type MyStringAlias = str # Compliant

type MyGenericAlias[T] = list[T]  # Compliant

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy