![github-actions[bot]](/assets/img/avatar_default.png)
You can preview this rule [here](https://sonarsource.github.io/rspec/#/rspec/S6796/python) (updated a few minutes after each push). ## Review A dedicated reviewer checked the rule description successfully for: - [ ] logical errors and incorrect information - [ ] information gaps and missing content - [ ] text style and tone - [ ] PR summary and labels follow [the guidelines](https://github.com/SonarSource/rspec/#to-modify-an-existing-rule) --------- Co-authored-by: joke1196 <joke1196@users.noreply.github.com> Co-authored-by: David Kunzmann <david.kunzmann@sonarsource.com>
77 lines
1.9 KiB
Plaintext
77 lines
1.9 KiB
Plaintext
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:
|
|
|
|
[source,python]
|
|
----
|
|
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:
|
|
|
|
[source,python]
|
|
----
|
|
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
|
|
|
|
[source,python,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
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
|
|
|
|
[source,python,diff-id=1,diff-type=compliant]
|
|
----
|
|
def func[T: str](a: T, b: int) -> T: # Compliant: the code is clear and concise.
|
|
...
|
|
----
|
|
|
|
|
|
== Resources
|
|
=== Documentation
|
|
|
|
* Python Documentation - https://docs.python.org/3.12/reference/simple_stmts.html#type[The type statement]
|
|
* Python 3.12 Release Notes - https://docs.python.org/3.12/whatsnew/3.12.html#pep-695-type-parameter-syntax[PEP 695: Type Parameter Syntax]
|
|
* PEP 695 - https://peps.python.org/pep-0695/[Type Parameter Syntax]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
|
|
== Implementation Specification
|
|
=== Message
|
|
(visible only on this page)
|
|
|
|
Use a generic type parameter for this function instead of a `TypeVar`.
|
|
|
|
'''
|
|
endif::env-github,rspecator-view[]
|