Skip to content

Commit 34f2390

Browse files
[3.11] Improve docs for typing.TypeAlias (GH-105372). (#105447)
(cherry picked from commit c5ec51e) Co-authored-by: Alex Waygood <[email protected]>
1 parent d0af527 commit 34f2390

File tree

1 file changed

+24
-3
lines changed

1 file changed

+24
-3
lines changed

Doc/library/typing.rst

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -786,13 +786,34 @@ These can be used as types in annotations and do not support ``[]``.
786786
.. data:: TypeAlias
787787

788788
Special annotation for explicitly declaring a :ref:`type alias <type-aliases>`.
789+
789790
For example::
790791

791-
from typing import TypeAlias
792+
from typing import TypeAlias
793+
794+
Factors: TypeAlias = list[int]
795+
796+
``TypeAlias`` is particularly useful for annotating
797+
aliases that make use of forward references, as it can be hard for type
798+
checkers to distinguish these from normal variable assignments:
799+
800+
.. testcode::
801+
802+
from typing import Generic, TypeAlias, TypeVar
803+
804+
T = TypeVar("T")
805+
806+
# "Box" does not exist yet,
807+
# so we have to use quotes for the forward reference.
808+
# Using ``TypeAlias`` tells the type checker that this is a type alias declaration,
809+
# not a variable assignment to a string.
810+
BoxOfStrings: TypeAlias = "Box[str]"
792811

793-
Factors: TypeAlias = list[int]
812+
class Box(Generic[T]):
813+
@classmethod
814+
def make_box_of_strings(cls) -> BoxOfStrings: ...
794815

795-
See :pep:`613` for more details about explicit type aliases.
816+
See :pep:`613` for more details.
796817

797818
.. versionadded:: 3.10
798819

0 commit comments

Comments
 (0)