From: Jelle Zijlstra Date: Wed, 7 Jun 2023 14:14:36 +0000 (-0700) Subject: [3.11] Improve docs for `typing.TypeAlias` (GH-105372). (#105447) X-Git-Tag: v3.11.5~320 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=34f23904e1e2e683dd6787ee51dd0294ea1f2b11;p=thirdparty%2FPython%2Fcpython.git [3.11] Improve docs for `typing.TypeAlias` (GH-105372). (#105447) (cherry picked from commit c5ec51ec8f4508e1f01f6d98ac8364a13da9bec7) Co-authored-by: Alex Waygood --- diff --git a/Doc/library/typing.rst b/Doc/library/typing.rst index 34803230822b..ba0a8d1550f7 100644 --- a/Doc/library/typing.rst +++ b/Doc/library/typing.rst @@ -786,13 +786,34 @@ These can be used as types in annotations and do not support ``[]``. .. data:: TypeAlias Special annotation for explicitly declaring a :ref:`type alias `. + For example:: - from typing import TypeAlias + from typing import TypeAlias + + Factors: TypeAlias = list[int] + + ``TypeAlias`` is particularly useful 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. + # 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