75 lines
1.9 KiB
Plaintext
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[]
|