2023-04-05 11:13:53 +02:00
|
|
|
== Why is this an issue?
|
|
|
|
|
|
|
|
Python 3.9 introduced built-in generic types such as `list[T]`, `dict[T]`, `set[T]` to make type hints more concise and easier to read.
|
|
|
|
These built-in types have the same functionality as their counterparts in the `typing` module, but are more readable and idiomatic.
|
|
|
|
|
|
|
|
Using types such as `typing.List` is confusing in the presence of the already existing built-in types.
|
|
|
|
This can also create inconsistencies when different parts of the codebase use different syntaxes for the same type.
|
|
|
|
|
|
|
|
== How to fix it
|
|
|
|
|
|
|
|
Replace the generic type from the `typing` module with its built-in counterpart:
|
|
|
|
|
|
|
|
[frame=all]
|
|
|
|
[cols="^1,^1"]
|
|
|
|
|===
|
|
|
|
|Legacy type|Replacement
|
|
|
|
|``++typing.List[int]++``|``++list[int]++``
|
|
|
|
|``++typing.Dict[str, int]++``|``++dict[str, int]++``
|
2023-04-05 12:41:26 +02:00
|
|
|
|``++typing.Set[str]++``|``++set[str]++``
|
|
|
|
|``++typing.FrozenSet[str]++``|``++frozenset[str]++``
|
2023-04-05 11:13:53 +02:00
|
|
|
|``++typing.Tuple[int, int]++``|``++tuple[int, int]++``
|
|
|
|
|``++typing.Tuple[int, ...]++``|``++tuple[int, ...]++``
|
|
|
|
|``++typing.Iterable[int]++``|``++collections.abc.Iterable[int]++``
|
|
|
|
|``++typing.Sequence[bool]++``|``++collections.abc.Sequence[bool]++``
|
|
|
|
|``++typing.Mapping[str, int]++``|``++collections.abc.Mapping[str, int]++``
|
|
|
|
|``++typing.Type[T]++``|``++type[T]++``
|
|
|
|
|===
|
|
|
|
|
|
|
|
Refer to PEP-585 in the Resources section for the full list of replacements.
|
|
|
|
|
|
|
|
=== Code examples
|
|
|
|
|
|
|
|
==== Noncompliant code example
|
|
|
|
|
|
|
|
[source,python]
|
|
|
|
----
|
|
|
|
import typing
|
|
|
|
|
|
|
|
def print_numbers(numbers: typing.List[int]) -> None:
|
|
|
|
for n in numbers:
|
|
|
|
print(n)
|
|
|
|
----
|
|
|
|
|
|
|
|
==== Compliant solution
|
|
|
|
|
|
|
|
[source,python]
|
|
|
|
----
|
|
|
|
def print_numbers(numbers: list[int]) -> None:
|
|
|
|
for n in numbers:
|
|
|
|
print(n)
|
|
|
|
----
|
|
|
|
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
- https://mypy.readthedocs.io/en/stable/builtin_types.html#generic-types[Mypy documentation on built-in generic types]
|
|
|
|
- https://peps.python.org/pep-0585/[PEP 585 - Type Hinting Generics In Standard Collections]
|
|
|
|
- https://docs.python.org/3/library/typing.html#generic-concrete-collections[Python documentation on generic collections]
|
|
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
== Implementation Specification
|
|
|
|
(visible only on this page)
|
|
|
|
|
|
|
|
include::../message.adoc[]
|
|
|
|
|
|
|
|
endif::env-github,rspecator-view[]
|