[doc] Leverage the fact that the actual types can now be indexed for typing (GH-22340)

This shows users that they can use the actual types. Using deprecated types is confusing.

This also prefers colections.abc.Sized instead of the alias typing.Sized. I guess the aliases were created to make it convenient to import all collections related types from the same place.

This should be backported to 3.9.

Automerge-Triggered-By: @gvanrossum
This commit is contained in:
Andre Delfino 2020-09-27 16:07:04 -03:00 committed by GitHub
parent a937ab45d6
commit d9ab95ff1f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 30 deletions

View File

@ -1084,19 +1084,15 @@ Glossary
Type aliases are useful for simplifying :term:`type hints <type hint>`. Type aliases are useful for simplifying :term:`type hints <type hint>`.
For example:: For example::
from typing import List, Tuple
def remove_gray_shades( def remove_gray_shades(
colors: List[Tuple[int, int, int]]) -> List[Tuple[int, int, int]]: colors: list[tuple[int, int, int]]) -> list[tuple[int, int, int]]:
pass pass
could be made more readable like this:: could be made more readable like this::
from typing import List, Tuple Color = tuple[int, int, int]
Color = Tuple[int, int, int] def remove_gray_shades(colors: list[Color]) -> list[Color]:
def remove_gray_shades(colors: List[Color]) -> List[Color]:
pass pass
See :mod:`typing` and :pep:`484`, which describe this functionality. See :mod:`typing` and :pep:`484`, which describe this functionality.

View File

@ -38,10 +38,9 @@ Type aliases
============ ============
A type alias is defined by assigning the type to the alias. In this example, A type alias is defined by assigning the type to the alias. In this example,
``Vector`` and ``List[float]`` will be treated as interchangeable synonyms:: ``Vector`` and ``list[float]`` will be treated as interchangeable synonyms::
from typing import List Vector = list[float]
Vector = List[float]
def scale(scalar: float, vector: Vector) -> Vector: def scale(scalar: float, vector: Vector) -> Vector:
return [scalar * num for num in vector] return [scalar * num for num in vector]
@ -51,11 +50,11 @@ A type alias is defined by assigning the type to the alias. In this example,
Type aliases are useful for simplifying complex type signatures. For example:: Type aliases are useful for simplifying complex type signatures. For example::
from typing import Dict, Tuple, Sequence from collections.abc import Sequence
ConnectionOptions = Dict[str, str] ConnectionOptions = dict[str, str]
Address = Tuple[str, int] Address = tuple[str, int]
Server = Tuple[Address, ConnectionOptions] Server = tuple[Address, ConnectionOptions]
def broadcast_message(message: str, servers: Sequence[Server]) -> None: def broadcast_message(message: str, servers: Sequence[Server]) -> None:
... ...
@ -64,7 +63,7 @@ Type aliases are useful for simplifying complex type signatures. For example::
# being exactly equivalent to this one. # being exactly equivalent to this one.
def broadcast_message( def broadcast_message(
message: str, message: str,
servers: Sequence[Tuple[Tuple[str, int], Dict[str, str]]]) -> None: servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
... ...
Note that ``None`` as a type hint is a special case and is replaced by Note that ``None`` as a type hint is a special case and is replaced by
@ -157,7 +156,7 @@ type hinted using ``Callable[[Arg1Type, Arg2Type], ReturnType]``.
For example:: For example::
from typing import Callable from collections.abc import Callable
def feeder(get_next_item: Callable[[], str]) -> None: def feeder(get_next_item: Callable[[], str]) -> None:
# Body # Body
@ -181,7 +180,7 @@ subscription to denote expected types for container elements.
:: ::
from typing import Mapping, Sequence from collections.abc import Mapping, Sequence
def notify_by_email(employees: Sequence[Employee], def notify_by_email(employees: Sequence[Employee],
overrides: Mapping[str, str]) -> None: ... overrides: Mapping[str, str]) -> None: ...
@ -191,7 +190,8 @@ called :class:`TypeVar`.
:: ::
from typing import Sequence, TypeVar from collections.abc import Sequence
from typing import TypeVar
T = TypeVar('T') # Declare type variable T = TypeVar('T') # Declare type variable
@ -235,7 +235,7 @@ class body.
The :class:`Generic` base class defines :meth:`__class_getitem__` so that The :class:`Generic` base class defines :meth:`__class_getitem__` so that
``LoggedVar[t]`` is valid as a type:: ``LoggedVar[t]`` is valid as a type::
from typing import Iterable from collections.abc import Iterable
def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None: def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:
for var in vars: for var in vars:
@ -266,7 +266,8 @@ This is thus invalid::
You can use multiple inheritance with :class:`Generic`:: You can use multiple inheritance with :class:`Generic`::
from typing import TypeVar, Generic, Sized from collections.abc import Sized
from typing import TypeVar, Generic
T = TypeVar('T') T = TypeVar('T')
@ -275,7 +276,8 @@ You can use multiple inheritance with :class:`Generic`::
When inheriting from generic classes, some type variables could be fixed:: When inheriting from generic classes, some type variables could be fixed::
from typing import TypeVar, Mapping from collections.abc import Mapping
from typing import TypeVar
T = TypeVar('T') T = TypeVar('T')
@ -288,13 +290,14 @@ Using a generic class without specifying type parameters assumes
:data:`Any` for each position. In the following example, ``MyIterable`` is :data:`Any` for each position. In the following example, ``MyIterable`` is
not generic but implicitly inherits from ``Iterable[Any]``:: not generic but implicitly inherits from ``Iterable[Any]``::
from typing import Iterable from collections.abc import Iterable
class MyIterable(Iterable): # Same as Iterable[Any] class MyIterable(Iterable): # Same as Iterable[Any]
User defined generic type aliases are also supported. Examples:: User defined generic type aliases are also supported. Examples::
from typing import TypeVar, Iterable, Tuple, Union from collections.abc import Iterable
from typing import TypeVar, Union
S = TypeVar('S') S = TypeVar('S')
Response = Union[Iterable[S], int] Response = Union[Iterable[S], int]
@ -303,9 +306,9 @@ User defined generic type aliases are also supported. Examples::
... ...
T = TypeVar('T', int, float, complex) T = TypeVar('T', int, float, complex)
Vec = Iterable[Tuple[T, T]] Vec = Iterable[tuple[T, T]]
def inproduct(v: Vec[T]) -> T: # Same as Iterable[Tuple[T, T]] def inproduct(v: Vec[T]) -> T: # Same as Iterable[tuple[T, T]]
return sum(x*y for x, y in v) return sum(x*y for x, y in v)
.. versionchanged:: 3.7 .. versionchanged:: 3.7
@ -408,7 +411,7 @@ to be explicitly marked to support them, which is unpythonic and unlike
what one would normally do in idiomatic dynamically typed Python code. what one would normally do in idiomatic dynamically typed Python code.
For example, this conforms to the :pep:`484`:: For example, this conforms to the :pep:`484`::
from typing import Sized, Iterable, Iterator from collections.abc import Sized, Iterable, Iterator
class Bucket(Sized, Iterable[int]): class Bucket(Sized, Iterable[int]):
... ...
@ -421,7 +424,7 @@ allowing ``Bucket`` to be implicitly considered a subtype of both ``Sized``
and ``Iterable[int]`` by static type checkers. This is known as and ``Iterable[int]`` by static type checkers. This is known as
*structural subtyping* (or static duck-typing):: *structural subtyping* (or static duck-typing)::
from typing import Iterator, Iterable from collections.abc import Iterator, Iterable
class Bucket: # Note: no base classes class Bucket: # Note: no base classes
... ...
@ -1371,10 +1374,10 @@ Asynchronous programming
The variance and order of type variables The variance and order of type variables
correspond to those of :class:`Generator`, for example:: correspond to those of :class:`Generator`, for example::
from typing import List, Coroutine from collections.abc import Coroutine
c = None # type: Coroutine[List[str], str, int] c = None # type: Coroutine[list[str], str, int]
... ...
x = c.send('hi') # type: List[str] x = c.send('hi') # type: list[str]
async def bar() -> None: async def bar() -> None:
x = await c # type: int x = await c # type: int