@@ -832,19 +832,41 @@ These can be used as types in annotations and do not support ``[]``.
832
832
.. data :: TypeAlias
833
833
834
834
Special annotation for explicitly declaring a :ref: `type alias <type-aliases >`.
835
+
835
836
For example::
836
837
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]"
838
857
839
- Factors: TypeAlias = list[int]
858
+ class Box(Generic[T]):
859
+ @classmethod
860
+ def make_box_of_strings(cls) -> BoxOfStrings: ...
840
861
841
- See :pep: `613 ` for more details about explicit type aliases .
862
+ See :pep: `613 ` for more details.
842
863
843
864
.. versionadded :: 3.10
844
865
845
866
.. deprecated :: 3.12
846
867
: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.
848
870
Note that while :data: `TypeAlias ` and :class: `TypeAliasType ` serve
849
871
similar purposes and have similar names, they are distinct and the
850
872
latter is not the type of the former.
0 commit comments