Skip to content

Commit 92ab560

Browse files
[3.12] Improve docs for typing.TypeAlias (GH-105372) (#105446)
Improve docs for `typing.TypeAlias` (GH-105372) (cherry picked from commit c5ec51e) Co-authored-by: Alex Waygood <[email protected]>
1 parent 117c153 commit 92ab560

File tree

1 file changed

+26
-4
lines changed

1 file changed

+26
-4
lines changed

Doc/library/typing.rst

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -832,19 +832,41 @@ These can be used as types in annotations and do not support ``[]``.
832832
.. data:: TypeAlias
833833

834834
Special annotation for explicitly declaring a :ref:`type alias <type-aliases>`.
835+
835836
For example::
836837

837-
from typing import TypeAlias
838+
from typing import TypeAlias
839+
840+
Factors: TypeAlias = list[int]
841+
842+
``TypeAlias`` is particularly useful on older Python versions for annotating
843+
aliases that make use of forward references, as it can be hard for type
844+
checkers to distinguish these from normal variable assignments:
845+
846+
.. testcode::
847+
848+
from typing import Generic, TypeAlias, TypeVar
849+
850+
T = TypeVar("T")
851+
852+
# "Box" does not exist yet,
853+
# so we have to use quotes for the forward reference on Python <3.12.
854+
# Using ``TypeAlias`` tells the type checker that this is a type alias declaration,
855+
# not a variable assignment to a string.
856+
BoxOfStrings: TypeAlias = "Box[str]"
838857

839-
Factors: TypeAlias = list[int]
858+
class Box(Generic[T]):
859+
@classmethod
860+
def make_box_of_strings(cls) -> BoxOfStrings: ...
840861

841-
See :pep:`613` for more details about explicit type aliases.
862+
See :pep:`613` for more details.
842863

843864
.. versionadded:: 3.10
844865

845866
.. deprecated:: 3.12
846867
:data:`TypeAlias` is deprecated in favor of the :keyword:`type` statement,
847-
which creates instances of :class:`TypeAliasType`.
868+
which creates instances of :class:`TypeAliasType`
869+
and which natively supports forward references.
848870
Note that while :data:`TypeAlias` and :class:`TypeAliasType` serve
849871
similar purposes and have similar names, they are distinct and the
850872
latter is not the type of the former.

0 commit comments

Comments
 (0)