[Python-checkins] [3.12] Improve docs for `typing.TypeAlias` (GH-105372) (#105446)
AlexWaygood
webhook-mailer at python.org
Wed Jun 7 09:46:02 EDT 2023
https://github.com/python/cpython/commit/92ab560ef5af9488476a49f2313a5aa7f7723329
commit: 92ab560ef5af9488476a49f2313a5aa7f7723329
branch: 3.12
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: AlexWaygood <Alex.Waygood at Gmail.com>
date: 2023-06-07T14:45:54+01:00
summary:
[3.12] Improve docs for `typing.TypeAlias` (GH-105372) (#105446)
Improve docs for `typing.TypeAlias` (GH-105372)
(cherry picked from commit c5ec51ec8f4508e1f01f6d98ac8364a13da9bec7)
Co-authored-by: Alex Waygood <Alex.Waygood at Gmail.com>
files:
M Doc/library/typing.rst
diff --git a/Doc/library/typing.rst b/Doc/library/typing.rst
index 05eebcf4b2e6..dc3b086d658a 100644
--- a/Doc/library/typing.rst
+++ b/Doc/library/typing.rst
@@ -832,19 +832,41 @@ These can be used as types in annotations and do not support ``[]``.
.. data:: TypeAlias
Special annotation for explicitly declaring a :ref:`type alias <type-aliases>`.
+
For example::
- from typing import TypeAlias
+ from typing import TypeAlias
+
+ Factors: TypeAlias = list[int]
+
+ ``TypeAlias`` is particularly useful on older Python versions for annotating
+ aliases that make use of forward references, as it can be hard for type
+ checkers to distinguish these from normal variable assignments:
+
+ .. testcode::
+
+ from typing import Generic, TypeAlias, TypeVar
+
+ T = TypeVar("T")
+
+ # "Box" does not exist yet,
+ # so we have to use quotes for the forward reference on Python <3.12.
+ # Using ``TypeAlias`` tells the type checker that this is a type alias declaration,
+ # not a variable assignment to a string.
+ BoxOfStrings: TypeAlias = "Box[str]"
- Factors: TypeAlias = list[int]
+ class Box(Generic[T]):
+ @classmethod
+ def make_box_of_strings(cls) -> BoxOfStrings: ...
- See :pep:`613` for more details about explicit type aliases.
+ See :pep:`613` for more details.
.. versionadded:: 3.10
.. deprecated:: 3.12
:data:`TypeAlias` is deprecated in favor of the :keyword:`type` statement,
- which creates instances of :class:`TypeAliasType`.
+ which creates instances of :class:`TypeAliasType`
+ and which natively supports forward references.
Note that while :data:`TypeAlias` and :class:`TypeAliasType` serve
similar purposes and have similar names, they are distinct and the
latter is not the type of the former.
More information about the Python-checkins
mailing list