mirror of
https://github.com/python/cpython.git
synced 2026-02-10 11:51:07 +00:00
[3.11] Improve docs for typing.TypeAlias (GH-105372). (#105447)
(cherry picked from commit c5ec51ec8f)
Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
This commit is contained in:
parent
d0af5272a7
commit
34f23904e1
1 changed files with 24 additions and 3 deletions
|
|
@ -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 <type-aliases>`.
|
||||
|
||||
For example::
|
||||
|
||||
from typing import TypeAlias
|
||||
from typing import TypeAlias
|
||||
|
||||
Factors: TypeAlias = list[int]
|
||||
Factors: TypeAlias = list[int]
|
||||
|
||||
See :pep:`613` for more details about explicit type aliases.
|
||||
``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]"
|
||||
|
||||
class Box(Generic[T]):
|
||||
@classmethod
|
||||
def make_box_of_strings(cls) -> BoxOfStrings: ...
|
||||
|
||||
See :pep:`613` for more details.
|
||||
|
||||
.. versionadded:: 3.10
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue