github-actions[bot] a36f03cb64
Create rule S6795: Generic type statement should not use TypeVars. (#3204)
You can preview this rule
[here](https://sonarsource.github.io/rspec/#/rspec/S6795/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>
2023-11-01 12:01:48 +01:00

86 lines
2.2 KiB
Plaintext

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:
[source,python]
----
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:
[source,python]
----
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:
[source,python]
----
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
[source,python,diff-id=1,diff-type=noncompliant]
----
from typing import TypeAlias
_T = TypeVar("_T")
type MyAlias = set[_T] # Noncompliant: a TypeVar is used as part of the type statement
----
==== Compliant solution
[source,python,diff-id=1,diff-type=compliant]
----
type MyAlias[T] = set[T] # Compliant: the new type statement syntax is used.
----
== 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 instead of a `TypeVar` in this `type` statement.
'''
endif::env-github,rspecator-view[]