rspec/rules/S6794/python/rule.adoc
github-actions[bot] 8671a03f6a
Create rule S6794: Type aliases should be declared with a "type" statement. (#3201)
You can preview this rule
[here](https://sonarsource.github.io/rspec/#/rspec/S6794/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 11:41:30 +01:00

75 lines
1.9 KiB
Plaintext

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:
[source,python]
----
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.
[source,python]
----
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
[source,python,diff-id=1,diff-type=noncompliant]
----
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
[source,python,diff-id=1,diff-type=compliant]
----
type MyStringAlias = str # Compliant
type MyGenericAlias[T] = list[T] # Compliant
----
== 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]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
=== Message
(visible only on this page)
Use a `type` statement instead of this `TypeAlias`.
'''
endif::env-github,rspecator-view[]