org.sonar.l10n.py.rules.python.S6796.html Maven / Gradle / Ivy
This rule raises an issue when a TypeVar
is used in a function instead of the generic function type syntax.
Why is this an issue?
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:
...
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, replace the usage of a TypeVar
as a parameter type with the generic type parameter syntax.
Code examples
Noncompliant code example
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.
...
Compliant solution
def func[T: str](a: T, b: int) -> T: # Compliant: the code is clear and concise.
...
Resources
Documentation
- Python Documentation - The type statement
- Python 3.12 Release Notes - PEP 695: Type Parameter
Syntax
- PEP 695 - Type Parameter Syntax
© 2015 - 2024 Weber Informatics LLC | Privacy Policy